Consider:
echo -e "a\nb\nc\nd\ne\nf\ng\nh" | sed '3,5a test'
This will match lines 3, 4 and 5.
But I am trying to match only lines 3 and 5 (not 4). And append 'test' after them.
Consider:
echo -e "a\nb\nc\nd\ne\nf\ng\nh" | sed '3,5a test'
This will match lines 3, 4 and 5.
But I am trying to match only lines 3 and 5 (not 4). And append 'test' after them.
echo ... | sed -e '3a test' -e '5a test'
If the operation is more complex than in this case then you can use a structure like this:
sed 'b pattern; : action; a \
lalala
b end; : pattern; 3b action; 5b action; : end'
I.e. you put all commands you need between b pattern; and b end;.
And you add all your patterns (line numbers or whatever) after : pattern;.
What happens is this:
The first command jumps over the action part (maybe it's easier to read if the patterns are at the beginning and b end; directly before the action part).
If a pattern matches then the execution jumps to the action part. After the action part execution jumps to the end.
I try to tidy this up:
sed '3b action; 5b action; b end; : action; a \
lalala
: end'
In a single line would be like:
sed "3b idAction; 5b idAction; b; : idAction; a test"
Portably, you need to write it:
sed '
3b action
5b action
b
: action
a\
lalala'
(b without label branches to the end, so you don't need an explicit end label, ; is valid a character in a label in standard sed implementations).
With sed (see @HaukeLaging's answer)
With awk:
$ echo -e "a\nb\nc\nd\ne\nf\ng\nh" | awk 'NR==3 || NR==5{$0=$0"\ntest"}1;'
With perl:
$ echo -e "a\nb\nc\nd\ne\nf\ng\nh" | perl -pe '$_ .="test\n" if $. == 3 || $. == 5'
As @HaukeLaging aleady said, this command does what you want:
sed -e'3a test' -e'5a test'
Now, this can become rather cumbersome to type if you want to match, e.g., 20 lines.
In these cases, assuming your shell supports brace expansion, you can use this command instead:
sed -e{3,5}'a test'
(Note that the braces and the comma must remain unquoted.)
As a result, the shell will pass the arguments to -e3a test and -e5a test to sed, which is exactly what the first command does.