How to delete lines with sed

In this post I am going to show you the use of delete in sed. I am using file named as data2 below are the contents of that file. None of the change in below cases is in place means the change will not get reflect in file content It will be shown on standard output only. To make the changes in place use -i option after sed in all commands.

[root@node1 network]# cat data2
I am unix engineer
Unix
UNIX
Linux
linux
LINUX
I work on Linux also.

Case 1 : How to delete specific lines from file.

[root@node1 network]# sed ‘1d;3d;5d’ data2
Unix
Linux
LINUX
I work on Linux also.

Case 2 : If want to delete range of lines.

[root@node1 network]# sed ‘1,5d’ data2
LINUX
I work on Linux also.

Case 3 : Deleting every line except 1 and 2.

[root@node1 network]# sed ‘1,2!d’ data2
I am unix engineer
Unix

Case 4 : How to delete line containing particular word. But it will not do case sensitive check.

[root@node1 network]# sed ‘/Linux/d’ data2
I am unix engineer
Unix
UNIX
linux
LINUX

Case 5 : Ignoring the case while deleting

[root@node1 network]# sed ‘/Linux/Id’ data2
I am unix engineer
Unix
UNIX

Case 6 : Will delete only lines starting with linux not those who containted word in line.

[root@node1 network]# sed ‘/^linux/Id’ data2
I am unix engineer
Unix
UNIX
I work on Linux also.

Case 7 : Using or in sed command Will delete lines containing “unix” or “linux” Point to be noted here it is not case sensitive.

[root@node1 network]# sed ‘/unix\|linux/d’ data2
Unix
UNIX
Linux
LINUX
I work on Linux also.

Case 8 : It will delete the unix (ignore case) starting from second line. Left the unix in first line as it is.

[root@node1 network]# sed ‘2,/unix/Id’ data2
I am unix engineer
Linux
linux
LINUX
I work on Linux also.

Case 9 : Delete the lines from 1 to 3 if they contain pattern unix or linux ignore case.

[root@node1 network]# sed ‘1,3{/unix\|linux/Id;}’ data2
Linux
linux
LINUX
I work on Linux also.

Case 10 : Delete the last line if it contains linux word in ignore case.

[root@node1 network]# sed ‘${/linux/Id;}’ data2
I am unix engineer
Unix
UNIX
Linux
linux
LINUX

 

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