Home > Back-end >  sed : Insert line after n lines following the pattern
sed : Insert line after n lines following the pattern

Time:11-03

Pls bear with me as I knew this questions has been asked a few time by others, yet I keep getting error with the suggested answers.

Original file:

    a1
    a2
    a3

product 2 
    b1
    b2
    b3

product 3
    c1
    c2
    c3

I would like to add string '1111111' two lines after match pattern 'product', fetch to a file 'out'. Such like:

product 1 
    a1
    a2
    1111111
    a3
product 2 
    b1
    b2
    1111111
    b3

product 3
    c1
    c2
    1111111
    c3

Those links I referred are suggesting the command as below but I get an error:

sed '/product/{n;n;a \    1111111'} file > out


sed: -e expression #1, char 0: unmatched `{'

I would like to achieve this using sed?

These are links I'm refering: Insert line after match using sed sed - insert line after X lines after match

Thank you.

CodePudding user response:

Either adding the -e option as Hatless suggested, or add one linebreak after your a command:

$ sed '/product/{n;n;a\    1111111 
}' f                                   
product 1 
    a1
    a2
    1111111
    a3

product 2 
    b1
    b2
    1111111
    b3

product 3
    c1
    c2
    1111111
    c3

CodePudding user response:

If ed is available/acceptable.

#!/bin/sh

ed -s file.txt <<-'EOF'
  g/product [0-9]\{1,\}$/ 2;t.\
  s/[^ ]*$/1111111/
  ,p
  Q
EOF

A separate ed script. (script.ed)

g/product [0-9]\{1,\}$/ 2;t.\
s/[^ ]*$/1111111/
,p
Q

Run that against the file with the ed utility.

ed -s file.txt < script.ed
  • Related