How to edit next line after pattern using sed?

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
  }'

Use the N;P;D cycle and attempt to substitute each time:

sed '$!N;s/\(foo\n\)#\(bar\)/\1\2/;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


Try:

sed -e '$!N;/foo\n#bar/s/\(\n\)#/\1/;P;D'

Tags:

Sed