Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Appending to the middle of a line in a textfile sed

Tags:

sed

I am completely new to sed script. I have been researching how to add text to a file and managed to get the text I want adding to the correct line in the file but can not find a way to add it to the correct position!

so the line 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 the line looks like:

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

Through trial and 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 do I go about adding it to the correct position?

like image 412
Sarah92 Avatar asked Jan 16 '23 10:01

Sarah92


1 Answers

There are many ways. One of them could be to search for last ' and use parentheses to save the data matched. I changed single quotes to double quotes because I want to match one of them inside the regular expression:

sed -i "/listen_addresses/ s/^\(.*\)\('\)/\1, 192.0.0.0\2/" testfile
  • ^\(.*\): Matches from the beginning until end of line (greeding).
  • \('\): Backtrack from the end until a '. So it will match the last one in the string.
  • \1: The content saved between first pair of parentheses.
  • , 192.0.0.0: Literal string.
  • \2: Content saved between second pair of parentheses.
like image 132
Birei Avatar answered Jan 30 '23 04:01

Birei