Friday, March 29, 2013

If you are working or using unix operating system, then you
must be proficient in sed language. Sed command in unix is very helpful for manipulation of file. While writing this article, I am considering this you are aware about the sed’s
little basics. Sed is a great utility which solves complex tasks by few lines
of code.

Sed stands for Stream
Editor. It is very powerful command to file manipulatation, filter lines
while reading file and transform text. Sed works both the way i.e. Sed can read
file and do operations on it or Sed can take inputs from pipe. If you are new learner then you will face
difficulty to understand the sed command but once you understood then It will
be easier to use as you need.

We are going to use below file in all 10 examples.

root@hello:~/test# cat salary.txt

1001,Ajay,Manager,25000

101,Satish,Founder,30000

302,Atul,CEO,26000

434,Raj,Senior Manager, 26000

1231,Kalyan,Human Resource,20000

The above salary database contains the columns as

Employee ID

Name

Designation

Salary

Basic Syntax of sed
command:

sed [options] {sed-commands}
{input-file}

sed [options] -e {sed-command-1} -e
{sed-command-2}{input-file}

Sed reads one line at a time from input file and executes
sed - command on that particular line. If we want to execute multiple commands
in a single line using several –e arguments, you can split them into multiple
lines using a backslash as below:

sed -n \

-e '/^mysql/ p' \

-e '/^other/ p' \

/etc/groups

10 special tricks of
Sed as follows :

1.Print the lines of input file after specific
interval i.e. print 1st, 3rd, 5th line of
file. Operator ~ used in an address
range. Its special meaning is to skip lines between commands. Below command you
can use to print the odd numbered lines
or to print the even numbered lines.

root@hello:~/test# sed -n '1~2 p' salary.txt

1001,Ajay,Manager,25000

302,Atul,CEO,26000

1231,Kalyan,Human Resource,20000

2.Print the lines matching with keyword.

root@hello:~/test# sed -n '/Atul/p' salary.txt

302,Atul,CEO,26000

3.Print the lines matching with keyword and 2
lines immediately after that. i.e. If matched keyword found then print 3 lines
including matched keyword line and 2 lines immediately after that line.

root@hello:~/test# sed -n
'/Atul/, +2p' salary.txt

302,Atul,CEO,26000

434,Raj,Senior Manager, 26000

1231,Kalyan,Human
Resource,20000

You can use above command for deleting lines in output by
using “d” instead of “p” option. i.e. if you want to delete lines starting from
1st match of “Atul” keyword till 4th line of file then
you can use it as