Search This Blog

Tuesday, June 22, 2010

Linux sed command.

In this article for sed command we will deal with below queries.

1)How to delete a line of a file specifying line number?
2)How to change case of letters/characters using sed?
3)How to delete blank lines of files.

How to delete a line of a file specifying line number?

content of temp.txt

a
b
c
d

We can delete a specific line of file using sed.
For example .
If we need to delete 2nd line of a file temp.txt .
run
#sed "2d" temp.txt
output:
a
c
d

What if we need to include a variable that defines the line number to be deleted.

#var=2; sed "${var}d" temp.txt
output:
a
c
d

(Note:here sed command doesnt make any changes the actual content of a file instead it is just shows the output after deleting the second line of a file.
For actually deleting the line in a file. you need to generate separate file using the output provided by sed command and then replace it with existing file using mv.)

for example.
above code can be written as.
#var=2; sed "${var}d" temp.txt > tmp.txt
#mv temp.txt tmp.txt
More information and different ways to accomplish the task can be found at.
http://www.unix.com/shell-programming-scripting/138366-how-would-i-delete-line-specific-line-number.html

How to change case of letters/characters using sed?


# cat /tmp/names.txt
rohan
arun
adam
john

# cat /tmp/names.txt |sed 'y/abcdefghijklmnopqrstuvwxyz/ABCDEFGHIJKLMNOPQRSTUVWXYZ/'
ROHAN
ARUN
ADAM
JOHN

Note:
y/source/dest/
Transliterate the characters in the pattern space which appear in source to the corresponding char-acter in dest.


3)How to delete blank lines of files.

Lets create a file called File1.txt .
# cat File1.txt
Agnes Gonxha Bojaxhiu more commonly known as Mother Teresa


Mother Teresa's Missionaries of Charity at the time of her death had 610 missions in 123 countries including hospices

Notice the two spaces between the lines.
Lets use delete to delete those line(you may use i operator instead of e for modifying the file File1.txt).
# sed -e '/^ *$/d' File1.txt
Agnes Gonxha Bojaxhiu more commonly known as Mother Teresa
Mother Teresa's Missionaries of Charity at the time of her death had 610 missions in 123 countries including hospices

Note:
^ (caret) : used for matching the beginning of the line.
$ (dollar sign) : used for matching end of the line.
* (asterisk) : used for matching zero or more occurrences of the previous character ( the previous character in this case is a space).


No comments:

Post a Comment