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";
}
serverstackqns
  • 764
  • 3
  • 16
  • 42

1 Answers1

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

Romeo Ninov
  • 5,263
  • 4
  • 20
  • 26
  • 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? – serverstackqns Nov 11 '22 at 14:45
  • Because `awk` only print the content. Let me add more explanations to the answer – Romeo Ninov Nov 11 '22 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? – serverstackqns Nov 11 '22 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 – Romeo Ninov Nov 11 '22 at 16:10
  • If you don't mind, can you please update the answer with this too. – serverstackqns Nov 11 '22 at 16:16
  • @serverstackqns, done. Maybe you should spend some time to learn `bash` scripting – Romeo Ninov Nov 11 '22 at 16:20
  • Let us [continue this discussion in chat](https://chat.stackexchange.com/rooms/140551/discussion-between-serverstackqns-and-romeo-ninov). – serverstackqns Nov 11 '22 at 16:20