Passing shell variables to awk and sed
By default awk and sed do not expand shell or system variables and do not pass their own variables back to the shell. To use shell variables awk and sed statements must be included in double-quotes. Here are a few examples:
1) You have a file (words.txt) containing a list of words and their replacements as shown below.
1234 blue redyellow greenstormy bluedark clearYou also have a text file (text.txt) where you need to replace the words from the list above with the corresponding alternatives.
1 blue flowers were growing on a yellow lawn under a dark stormy skyHere’s a shell script to do it:
123456789 #!/bin/kshcat words.txt | while read LINEdoO=$(echo "$LINE" | awk '{print $1}')R=$(echo "$LINE" | awk '{print $2}')cat text.txt | sed "s/$O/$R/g" > tmp.txtmv tmp.txt text.txtdoneThe resulting text.txt file would read:
1 red flowers were growing on a green lawn under a clear blue sky
-
Joey 01
