Adding to the middle of a line in a sed text file

I am completely new to sed script. I studied how to add text to a file, and I managed to get the text that I want to add to the correct line in the file, but cannot find a way to add it to the correct position!

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

listen_addresses = 'localhost, 192.0.0.0' # what IP address(es) to listen on; 

I want to add an IP so that the line looks like this:

  listen_addresses = 'localhost, 192.0.0.0, 192.0.0.0' # what IP address(es) to listen on; 

Through the trial version and the error, I only have:

  sed -i '/listen_addresses/ s/.*/&,192.0.0.0/' testfile 

which gives:

  listen_addresses = 'localhost, 192.0.0.0' # what IP address(es) to listen on; 192.168.0.0 

How can I add it to the right position?

+4
source share
2 answers

There are many ways. One of them may be to search for the latter ' and use parentheses to keep consistent data. I changed single quotes to double quotes because I want them to match one of them in the regex:

 sed -i "/listen_addresses/ s/^\(.*\)\('\)/\1, 192.0.0.0\2/" testfile 
  • ^\(.*\) : match from beginning to end of line (greed).
  • \('\) : Rollback from end to ' . Thus, it will match the last in the line.
  • \1 : content stored between the first pair of parentheses.
  • , 192.0.0.0 : A literal string.
  • \2 : content is stored between the second pair of parentheses.
+7
source

Just replace the ' # part with the line:

 sed -i "/listen_addresses/ s/' #/, 192.0.0.0' #/" testfile 

Please note that I used double quotes, so a single quote can be easily inserted.

+2
source

Source: https://habr.com/ru/post/1437546/


All Articles