0

I have been researching how to add text to a line in file.

so the line I have in the text file looks like this

hosts allow = 192.168.122. 172.24.0 

i want to add IP so line looks like

hosts allow = 192.168.122.  192.12.0.  172.24.0

Through trial and error I only have:

sed -i '/allow/ s/.*/&,192.12.0./' testfile

which gives:

hosts allow = 192.168.122. 172.24.0. 192.12.0.
Rishav
  • 1
  • 2

2 Answers2

1

Using awk to insert the string as the second to last field on the line:

$ awk '/allow/ { $(NF+1) = $NF; $(NF-1) = "192.12.0." } { print }' file
hosts allow = 192.168.122. 192.12.0. 172.24.0

The first block will be executed for any line in file containing the string allow. It will first move the last field, $NF, one step further along, to $(NF+1). This increases NF by one. It then assigns the string to the second to last field, $(NF-1).

All lines are then printed.

Redirect the output from this to a new file and move that file into place:

awk ...as above... file >file.new && mv file.new file
Kusalananda
  • 333,661
0
sed 's/= [^ ]*/& 192.12.0/'

Captures the = sign, the space and all characters before the next space. That is, this part = 192.168.122.. Then, replaces all matching characters to themselves - & (in other words, doesn't change this part, just returns it back), plus adds the needed ip 192.12.0.

Input

hosts allow = 192.168.122. 172.24.0

Output

hosts allow = 192.168.122. 192.12.0 172.24.0
MiniMax
  • 4,123