Using sed, how do I search for a line ending with foo and then edit the next line if it starts with #bar?
Or put another way, I want to remove a comment # from the next line if it starts with #bar and the previous line ends in foo.
For example:
This is a line ending in foo #bar is commented out There are many lines ending in foo #bar commented out again
I tried:
sed -i 's/^foon#bar/foonbar/' infile
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
sed '/foo$/{n;s/^#bar/bar/;}'
is a literal translation of your requirement. n is for next.
Now that doesn’t work in cases like:
line1 foo #bar line2 foo #bar
Or:
line1 foo line2 foo #bar
As the line that is pulled into the pattern space by n is not searched for foo.
You could address it by looping back to the beginning after the next line has been pulled into the pattern space:
sed '
:1
/foo$/ {
n
s/^#bar/bar/
b1
}'
Method 2
Use the N;P;D cycle and attempt to substitute each time:
sed '$!N;s/(foon)#(bar)/12/;P;D' infile
this removes the leading # from #bar only if it follows a line ending in foo otherwise it just prints the pattern space unmodified.
Apparently, you want to uncomment US mirrors in /etc/pacman.d/mirrorlist which is a whole different thing:
sed -e '/United States/,/^$/{//!s/^#//' -e '}' /etc/pacman.d/mirrorlist
This will uncomment all mirrors in the US section in /etc/pacman.d/mirrorlist
Method 3
Try:
sed -e '$!N;/foon#bar/s/(n)#/1/;P;D'
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0