Dealing with multiline pattern using sed

In this post I am going to show you in simple way the difference while dealing with single line and multiline patterns.

I am taking the below file as example to show you the differences.

[root@node1 ~]# cat data7
hello world
my name is vikrant
i am happy

Case 1 : Captial N will read the new line of input and append it to contents of pattern space. They are separated by \n (newline).

In below example I am searching of vikrant at end of every line in data7 file. I found it on second line and after that I read the next line using N I substitue the \n with space option by which newline and line selected as per pattern are concatenated, to give the better understanding.

[root@node1 ~]# sed ‘/vikrant$/{N;s/\n/ /;}’ data7
hello world
my name is vikrant i am happy

Now if I am going to do the same thing by replacing N with small n output is different. Because n will print the pattern space then It will read the new line. It doesn’t created multiline pattern space as in case of N

[root@node1 ~]# sed ‘/vikrant$/{n;s/\n/ /;}’ data7
hello world
my name is vikrant
i am happy

Case 2 : Captial “P” is used to output the first portion of a multiliner pattern space up to embedded newline.

Continuing for previous case. Showing the usage of P vs p. after reading the line “my name is vikrant \n i am happy” But due to P option It is displaying only first part again i.e. “my name is vikrant”

[root@node1 ~]# sed ‘/vikrant$/{N;P}’ data7
hello world
my name is vikrant
my name is vikrant
i am happy

But p will display the whole thing again “my name is vikrant \n i am happy”

On other hand small “p” will display the whole portion included embedded new line.

[root@node1 ~]# sed ‘/vikrant$/{N;p}’ data7
hello world
my name is vikrant
i am happy
my name is vikrant
i am happy

Case 3 : Now moving with D and d.

Extending scenario from Case 2. As P will print only the first pattern space not the embedded one. In same way D will delete only the first pattern space. Now combination of N,P,D can be used to work on multiline.

[root@node1 ~]# sed ‘/vikrant$/{N;P;D;}’ data7
hello world
my name is vikrant
i am happy

If we are trying to do the same thing with d it will delete the whole line included the embedded one.

[root@node1 ~]# sed ‘/vikrant$/{N;P;d;}’ data7
hello world
my name is vikrant

 

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s