Tuesday, 24 July 2012

Shell Scripting

1. To remove all the empty lines in a file
            #grep -v "^$" testfile where testfile - filename

^ - means beginning of the line
$ - end of the line
           
Above characters are called anchors . 

One more example : 

grep -i  ^ts testfile

Which will display the line which has "ts" in the beginning of the lines


Usage of sed:

Deleting all the lines matching a particular pattern:

Take the vfstab file where you want to delete all the lines containing tmpfs

#sed /tmpfs/d vfstab

Where d indicates delete all the lines matching pattern tmpfs
similarly p means print. Lets do one exercise.

I want to print only the ufs filesystem specified in vfstab file

#sed -n /ufs/p vfstab

Where -n option is used to print only those lines matching the pattern else all lines will be displayed.

There are few operators which are commonly used

p - print
d - delete
g - global - which means operation is performed on all the occurrence of the pattern.
s - substitute

All other operators, i believe is self explanatory.
 


# echo "suman mandal" | sed 's/\([a-z]*\) \([a-z]*\)/\2 \1/'

Output of the above command will
mandal suman




No comments:

Post a Comment