Rishabh Rishabh - 2 months ago 9
Linux Question

Using Variable in awk command

I want to add a word at the end of each line in my text file which is stored in variable. whenever i execute shell script instead of concatenate content stored in variable variable itself get concatenated. Below is the example for same:

Input:

cat output2.txt

12345

att1=Ramesh^Mumbai

awk '{print $0"^$att1"}' output2.txt >output3.txt


output:

12345^att1


Desired Output:

12345^Ramesh^Mumbai

Answer

Try this:

awk -v att1='Ramesh^Mumbai' -v OFS='^' '{print $0,att1}'

-v option allows to pass variable to awk

OFS is the output field separator (that will replace the , in the print statement by ^)