Skip to content
Advertisement

escape one variable but not the other in awk

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

The problem here is that I want the variable “var” to be interpreted (it works) and the variable $OTHERVAR not to be interpreted, and this I what I can’t manage to do.

In the end, I want to do this:

I have a variable

MYVAR=export OTHER_VAR=$OTHER_VAR:some_text

I want to replace, in /etc/myfile, the following pattern :

export OTHER_VAR=$OTHER_VAR:/folder/bin by export OTHER_VAR=$OTHER_VAR:some_text:/folder/bin.

I hope I made myself clear …

Thanks in advance !

Sylvain

Advertisement

Answer

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:

  • We’re escaping the $ 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.
  • Using single quotes for literal strings ensures that no shell interpolation takes place within them.
  • Using {print} is a bit easier for readers to understand than a bare 1 in awk.
  • Excluding variable names with meaning to the OS or shell, use of lower-case characters in variable names is in line with POSIX-specified convention. See http://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap08.html, fourth paragraph.
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement