Bash: Using shell or environment variables in awk output

If you are in the middle of a text processing pipeline, and need to insert a shell or environment variable into the output of awk, you can use the “-v” flag.

Here are two files containing animal classifications:

$ echo -e "shark=fish\ndolphin=mammal" > ocean.txt
$ echo -e "dog=mammal\neagle=bird" > land.txt

By passing the loop variable in using “-v”, it can be used in the awk output.

$ for tfile in ocean land; do cat $tfile.txt | awk -v tfile=$tfile -F'=' '{ printf("A %s is a %s and lives in %s\n",$1,$2,tfile) }'; done

A shark is a fish and lives in ocean
A dolphin is a mammal and lives in ocean
A dog is a mammal and lives in land
A eagle is a bird and lives in land

This can be used for any shell or environment variable.

REFERENCES

awk man page

cyberciti, passing shell variables to awk

tecnmint, using awk with BEGIN and END

 

NOTES

another example of using outside variable inside awk printf

thedir="/tmp"
ls $thedir | awk -v thedir=$thedir '{ printf "directory %s has file %s\n",thedir,$1 }'