0

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"; } 
3
  • do you want to get line variable from file or from other source? Commented Nov 11, 2022 at 13:30
  • And what is the exact format of the copy.txt file? Commented 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. Commented Nov 11, 2022 at 13:48

1 Answer 1

0

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:

line=192.168.0.10 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

7
  • 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? Commented Nov 11, 2022 at 14:45
  • Because awk only print the content. Let me add more explanations to the answer Commented Nov 11, 2022 at 15:19
  • Thanks, it works, but in line1 should be updated with the value along with "" (double quotes) example: "192.168.0.10". Now it is coming as 192.168.10.0. How can I achieve that? Commented Nov 11, 2022 at 16:02
  • @serverstackqns, before exec the awk you should run command like line=192.168.0.10 and in awk variable line1 will get this value Commented Nov 11, 2022 at 16:10
  • If you don't mind, can you please update the answer with this too. Commented Nov 11, 2022 at 16:16

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.