1

I want to do two things by sed when matching a pattern:

  1. Replace the pattern with a string
  2. Append another string after this line

Such as the original content in a text file is:

abc
123
edf

I want to replace 123 to XXX and append YYY after the line:

abc
XXX
YYY
edf

I tried to do this by sed '/123/{s/123/XXX;a\YYY\}', but it gave an error: Unmatched "{".

It seemed that command a treats all characters after it as text to append. So how can I make a know the end position of the text for append?

Mark Setchell
  • 191,897
  • 31
  • 273
  • 432
WKPlus
  • 6,955
  • 2
  • 35
  • 53

4 Answers4

2

It works the using actual newlines (tested with GNU Sed 4.2.2):

sed '/123/ {
    s/123/XXX
    a\YYY
}' < $input_file
shadowtalker
  • 12,529
  • 3
  • 53
  • 96
2

This might work for you (GNU sed):

sed '/123/c\XXX\nYYY' file

This uses the c command to change the line matched by the pattern.

Or if you prefer to substitute and append:

sed 's/123/XXX/;T;a\YYY' file

Or:

sed -e '/123/{s//XXX/;a\YYY' -e '}' file

Or:

sed $'/123/{s//XXX/;a\YYY\n}' file 
potong
  • 55,640
  • 6
  • 51
  • 83
1

In bash this could be the simplest one using sed:

sed  -e $'s/123/XXX\\nYYY/' file

From bash man:

Words of the form $'string' are treated specially. The word expands to string, with backslash-escaped characters replaced as specified by the ANSI C standard

Example

$ sed  -e 's/123/XXX\\nYYY/' file
abc
XXX\nYYY
edf

But $'string' will produce:

$ sed  -e $'s/123/XXX\\nYYY/' file
abc
XXX
YYY
edf
Juan Diego Godoy Robles
  • 14,447
  • 2
  • 38
  • 52
0
$ sed 's/123/XXX\'$'\nYYY/' a
abc
XXX
YYY
def
$

Where...

$ cat a
abc
123
def
$
mauro
  • 5,730
  • 2
  • 26
  • 25