0

The sed's document states

P

Print up to the first embedded newline of the current pattern space.

I did some experiment and trying to understand it. Below is my testing.

root:[~]# seq 3 | sed -n '/2/{iline1\nline2;P}'
sed: -e expression #1, char 0: unmatched `{'
root:[~]#

Here -n disables the auto-printing of the pattern space. /2/ matches the second line, which has the content 2. So when the second line has been matched, the pattern space has the content 2. The i command inserts line1\nline2 and a newline character to the beginning of the pattern space. So the pattern space should have the content line1\nline2\n2. Now the P command print up to the first new line, so line1 should be printed and should be the result of the whole command. Is my understanding correct? Why the error? Thanks in advance.

0

2 Answers 2

3

The i command does not insert anything into the pattern space. It writes its text to standard output.

Here's a better example:

$ cat file
line 1
line 2
line 3
line 4
$ sed -n 'N;P' file
line 1
line 3

The sed script reads a line into the pattern space. The N command appends the next line of input to the pattern space with an embedded newline in-between. The P writes the first line up to the newline inserted by N in the pattern space. The next cycle starts (no output at the end of the cycle due to the -n).

3

For the error: you need an literal (unbackslashed) newline after the text of a i command. In GNU sed you can get away with

seq 3 | sed -n -e '/2/{iline1\nline2' -e 'P}'

just as you got away with the \n for a newline.

Otherwise:

seq 3 | sed -n '/2/{i\
line1\
line2
P;}'

As to your claims: the i command "inserts" into the output file, not into the pattern space. In the corrected example, the pattern space will be 2, which P will print in its entirety, since it contains no newline.

Generally, the GNU sed's manpage is a mess, and should only be consulted for the GNU extensions. I recommend the standard spec, which is much more readable:

[1addr]i\
text
       Write text to standard output.
[2addr]P
       Write the pattern space, up to the first <newline>, to standard
       output.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .