Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between p and P in sed?

Can anyone explain what is the difference between p and P in Sed?

Suppose I want to print lines containing gmail in the below file using both p and P give the same output:

$ cat abc.txt 
Gmail 10
Yahoo 20
Rediff 18

$ sed -n /Gmail/p abc.txt
Gmail 10 

$ sed -n /Gmail/P abc.txt
Gmail 10 

What is the difference between p and P?

like image 221
gopesh Avatar asked Nov 25 '13 13:11

gopesh


1 Answers

In sed, p prints the addressed line(s), while P prints only the first part (up to a newline character \n) of the addressed line. If you have only one line in the buffer, p and P are the same thing, but logically p should be used.

Let's look at an academic but easy example. Let's assume we want to print line number 1, we can do

$ echo "line 1
$ This is line 2" | sed -n '1p'
> line 1

We could also do

$ echo "line 1
$ This is line 2" | sed -n '1P'
> line 1

Both commands do the same thing, since there is no newline character in the buffer.

But now we use the N command to add a second line into the buffer:

$ echo "line 1
$ This is line 2" | sed -n '1{N; p}'
> line 1
> This is line 2

Now we had 2 lines in the buffer and we print them both with p.

$ echo "line 1
$ This is line 2" | sed -n '1{N; P}'
> line 1

Again we had 2 lines in the buffer, but we printed only the first one, since we were using P and not p.

like image 109
pfnuesel Avatar answered Oct 15 '22 08:10

pfnuesel