Friday, 8 May 2015

awk and sed command in linux - examples



awk


The awk command is powerful method for processing or analyzing text files, in particular data files that are organized by lines (rows) and columns.

Simple awk commands can be run from the command line. More complex tasks should be written as awk programs (so-called awk scripts) to a file.


I have a file named  awkexample.txt, I am going to extract a particular column from this file.

         anusree@anusree-VirtualBox:~$ awk '{print $2;}' awkexample.txt 



In this file the second column is x 1 x 2 x 3 like that , iam going to extract only the integer with "if" condition.

anusree@anusree-VirtualBox:~$ awk '{if($2!~"x") print $2;}' awkexample.txt



sed

Sed is a Stream Editor used for modifying the files in unix (or linux). Whenever you want to make changes to the file automatically, sed comes in handy to do this.

Consider the file sed1.txt





1)
Replacing or substituting string

Sed command is mostly used to replace the text in a file. The below simple sed command replaces the word "unix" with "linux" in the file.







anusree@anusree-VirtualBox:~$ sed 's/unix/linux/' sed1.txt
The above sed command replaces the first occurrence of the pattern in each line and it won't replace the second, third...occurrence in the line.






2)
Replacing the nth occurrence of a pattern in a line.

If you want to replace nth occurance of the word.

anusree@anusree-VirtualBox:~$ sed 's/unix/linux/2' sed1.txt


3)
Replacing all the occurrence of the pattern in a line.

The substitute flag /g (global replacement) specifies the sed command to replace all the occurrences of the string in the line.



4)
Replacing from nth occurrence to all occurrences in a line.

 anusree@anusree-VirtualBox:~$ sed 's/unix/linux/2g' sed1.txt

It will replace all the word unix to linux from the second occurance in the first line