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?
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.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With