· df · 1 min read

Substitute data with a variable using "awk and sed"

Technology

Have you ever tried out substituting particular string with a variable? I thought it was easy.. but it is  NOT !! There are plenty of examples showing subsituting a fixed string with another fixed String.


 # substitute (find and replace) “foo” with “bar” on each line
awk ‘{sub(/foo/,“bar”);print}’ # replaces only 1st instance
awk ‘{gsub(/foo/,“bar”);print}’ # replaces ALL instances in a line


But I had an issue to substitute  “foo” with value of “$bar” .. This is not easy. I did a workaround of using “awk” and “sed”

The scenario in front of me is to list a directory with files and the hostname of the Server.
thisHost=hostname
ls -lrt | tail +2 | awk ‘{ print “thishost|”$9}’ | sed “s/thishost/$thisHost/”

 

tail +2 will remove the headers

The trick is to print  literal “thishost” and replace “thishost” literal using the value within sed.