How can I add a variable within awk command? below is my command:

cat /home/ubuntu/test/copy.txt | awk 'NR==21{print ".host = "$line";"}1'

$line is basically an IP address which is retrieved from a text file. With the above command the output looks like

.host = ;

Any immediate help would be really appreciated.

Format of copy.txt

backend default {
#.host = value; need to be here
.port = "8080";
  • do you want to get line variable from file or from other source? Nov 11, 2022 at 13:30
  • And what is the exact format of the copy.txt file? Nov 11, 2022 at 13:32
  • @RomeoNinov- please check my update. also, regarding line, I am already capturing it from a file using while loop. Nov 11, 2022 at 13:48

1 Answer 1


The variables in awk can be transferred from shell on this way:

awk -v variable=$line '.....

and used inside on this way:

awk -v line1=$line 'NR==21 {print ".host = "line1";"}1'

The variable should be set beforehand in bash so the things become:

awk -v line1=$line 'NR==21 {print ".host = "line1";"}1' /path/to/file ...

Also you do not need cat, just use this way:

awk '....' /home/ubuntu/test/copy.txt

To store the output in a file you should use something like:

awk '....' /home/ubuntu/test/copy.txt >/home/ubuntu/test/new_copy.txt

and the result will be stored in /home/ubuntu/test/new_copy.txt

  • It works, however the file doesnt seem to be saved. The reason is I am able to see the file with the update printed, but checking the file in another window, there's no content in line 21. Any idea why? Nov 11, 2022 at 14:45
  • Because awk only print the content. Let me add more explanations to the answer Nov 11, 2022 at 15:19
  • Thanks, it works, but in line1 should be updated with the value along with "" (double quotes) example: "". Now it is coming as How can I achieve that? Nov 11, 2022 at 16:02
  • @serverstackqns, before exec the awk you should run command like line= and in awk variable line1 will get this value Nov 11, 2022 at 16:10
  • If you don't mind, can you please update the answer with this too. Nov 11, 2022 at 16:16

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.