If you just want the next line after a pattern, this sed
command will work
sed -n -e '/pattern/{n;p;}'
-n
supresses output (quiet mode);
-e
denotes a sed command (not required in this case);
/pattern/
is a regex search for lines containing the literal combination of the characters pattern
(Use /^pattern$/
for line consisting of only of “pattern”;
n
replaces the pattern space with the next line;
p
prints;
For example:
seq 10 | sed -n -e '/5/{n;p;}'
Note that the above command will print a single line after every line containing pattern
. If you just want the first one use sed -n -e '/pattern/{n;p;q;}'
. This is also more efficient as the whole file is not read.
This strictly sed
command will print all lines after your pattern.
sed -n '/pattern/,${/pattern/!p;}
Formatted as a sed
script this would be:
/pattern/,${
/pattern/!p
}
Here’s a short example:
seq 10 | sed -n '/5/,${/5/!p;}'
/pattern/,$
will select all the lines from pattern
to the end of the file.
{}
groups the next set of commands (c-like block command)
/pattern/!p;
prints lines that doesn’t match pattern
. Note that the ;
is required in early versions, and some non-GNU, of sed
. This turns the instruction into a exclusive range - sed
ranges are normally inclusive for both start and end of the range.
To exclude the end of range you could do something like this:
sed -n '/pattern/,/endpattern/{/pattern/!{/endpattern/d;p;}}
/pattern/,/endpattern/{
/pattern/!{
/endpattern/d
p
}
}
/endpattern/d
is deleted from the “pattern space” and the script restarts from the top, skipping the p
command for that line.
Another pithy example:
seq 10 | sed -n '/5/,/8/{/5/!{/8/d;p}}'
If you have GNU sed you can add the debug switch:
seq 5 | sed -n --debug '/2/,/4/{/2/!{/4/d;p}}'
Output:
SED PROGRAM:
/2/,/4/ {
/2/! {
/4/ d
p
}
}
INPUT: 'STDIN' line 1
PATTERN: 1
COMMAND: /2/,/4/ {
COMMAND: }
END-OF-CYCLE:
INPUT: 'STDIN' line 2
PATTERN: 2
COMMAND: /2/,/4/ {
COMMAND: /2/! {
COMMAND: }
COMMAND: }
END-OF-CYCLE:
INPUT: 'STDIN' line 3
PATTERN: 3
COMMAND: /2/,/4/ {
COMMAND: /2/! {
COMMAND: /4/ d
COMMAND: p
3
COMMAND: }
COMMAND: }
END-OF-CYCLE:
INPUT: 'STDIN' line 4
PATTERN: 4
COMMAND: /2/,/4/ {
COMMAND: /2/! {
COMMAND: /4/ d
END-OF-CYCLE:
INPUT: 'STDIN' line 5
PATTERN: 5
COMMAND: /2/,/4/ {
COMMAND: }
END-OF-CYCLE: