I'm facing a problem with awk in Linux. I would like to do make this script work :
awk -v var="$MYVAR" "{gsub(/export OTHER_VAR=\$OTHER_VAR:/, "var")}1" /etc/myfile
MYVAR=export OTHER_VAR=\$OTHER_VAR:some_text
export OTHER_VAR=$OTHER_VAR:/folder/bin
export OTHER_VAR=$OTHER_VAR:some_text:/folder/bin
test_document='export OTHER_VAR=$OTHER_VAR:whatever'
search_regex='^export OTHER_VAR=[$]OTHER_VAR:'
replace_str='export OTHER_VAR=$OTHER_VAR:some_text:'
awk -v search_regex="$search_regex" \
-v replace_str="$replace_str" \
'{gsub(search_regex, replace_str)} {print}' <<<"$test_document"
...properly emits as output:
export OTHER_VAR=$OTHER_VAR:some_text:whatever
Note some changes:
$
in the regex as [$]
. Unlike \$
, this is parsed consistently across all quoting contexts: It is explicitly generating a regex character class, rather than having any other potential meaning.{print}
is a bit easier for readers to understand than a bare 1
in awk
.