Saturday 4 January 2014

sed handy commands

Just exploring sed utility , so thought of sharing my learnings.

[root@localhost] $ cat example_file
 This is the first line of an example text.
 It is a text with erors.
 Lots of erors.
 So much erors, all these erors are making me sick.
 This is a line not containing any errors.
 This is the last line.

Print the lines containing the string "errors"
 [root@localhost] $ sed -n '/errors/p' example_file
 This is a line not containing any errors.

Print the lines not containing the string "errors"
[root@localhost] $ sed '/errors/d' example_file
This is the first line of an example text.
It is a text with erors.
Lots of erors.
So much erors, all these erors are making me sick.
This is the last line.

Print lines 2,3 and 4
root@localhost] $ sed -n '2,4p' example_file
It is a text with erors.
Lots of erors.
So much erors, all these erors are making me sick.

Print other lines excluding lines 2,3,4
[root@localhost] $ sed '2,4d' example_file
This is the first line of an example text.
This is a line not containing any errors.
This is the last line.

Insert a string at the beginning of lines 1,2
[root@localhost] $ sed -e 's/^/Hi, /g' -e  '3,6d' example_file
Hi, This is the first line of an example text.
Hi, It is a text with erors.


Removing Blank lines from a file
[root@localhost] $ sed /^$/d -i example_file

 

No comments:

Post a Comment