-2

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.

romainl
  • 186,200
  • 21
  • 280
  • 313
Grace
  • 440
  • 3
  • 6
  • 21
  • 1
    `sed -e '/^product/{n;n;a1111111' -e '}' file` – HatLess Nov 03 '22 at 09:50
  • 3
    *would like to achieve this using sed* then please explain why have you use `awk` tag – Daweo Nov 03 '22 at 09:55
  • Thank you Hatless. Your suggestion works for me. Would you mind explain why I need two separated -e switched here? Also, wonder why some other sed command I don't need -e at all? – Grace Nov 03 '22 at 23:59
  • Hi Hatless, I changed the code a bit so that it only fetch string to certain product. However I get error: Unmatched ". – Grace Nov 04 '22 at 00:58
  • Here is my code. May I know where goes wrong? foreach product (`cat product_list.txt`) sed -e "/(${product}/{n;n;n;n;n;a \ product_type : \"Industrial Goods\" ; ' -e '}" file > out end – Grace Nov 04 '22 at 00:59

1 Answers1

1

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
Kent
  • 189,393
  • 32
  • 233
  • 301
  • Thanks you Kent. Same as what Hatless suggested, this works for me, however I don't understand why need a break before the closing braces. – Grace Nov 04 '22 at 00:06