Nov 25, 2012

Awk Examples



1) To fetch selected columns from a command using AWK

e.g.,

>> ls -l

-rw-r----- 1 kotaprax users 203 Nov 22 12:51 new.txt
-rw-r----- 1 kotaprax users 100 Nov 22 12:51 new1.txt
-rw-r----- 1 kotaprax users 126 Nov 23 12:57 output.txt
-rw-r----- 1 kotaprax users 282 Nov 23 10:18 test.txt
-rw-r----- 1 kotaprax users  17 Nov 16 15:25 test1.txt

From the abvoe command, we are deriving some columns

>> ls -l | awk '{print $3 "\t" $8 "\t" $9}'
             
kotaprax        12:51   new.txt
kotaprax        12:51   new1.txt
kotaprax        12:57   output.txt
kotaprax        10:18   test.txt
kotaprax        15:25   test1.txt



2) How to print first column from the file using AWK

e.g.,

>> cat test.txt
prabhath kota
lakshmi muvvala
PRABHATH KOTA
LAKSHMI MUVVALA


>>awk '{print $1}' test.txt
(or)
>>awk < test.txt '{ print $1 }'

o/p:
>>cat test.txt
prabhath
lakshmi
PRABHATH
LAKSHMI


3) How to copy the files using AWK

>> ls
a.txt
b.txt
c.txt

It will copy file.txt to file.txt.new for all the txt files

>>ls *.txt | awk '{print "cp "$1" "$1".new"}' | sh

o/p:

>> ls
a.txt
b.txt
c.txt
a.txt.new
b.txt.new
c.txt.new


4) How to list only directories using awk

>>ls
a.txt
b.txt
c.txt
prabhath_test

o/p:

>> ls -l | grep '^d'
#Lists only directories, since directories start with
drwxr-x--- 2 kotaprax users 1024 Nov 23 13:57 prabhath_test


>>ls -l | grep -v '^d' #Lists only files but not directories
-rw-r----- 1 kotaprax users 203 Nov 22 12:51 a.txt
-rw-r----- 1 kotaprax users 282 Nov 23 10:18 b.txt
-rw-r----- 1 kotaprax users  17 Nov 16 15:25 c.txt


5) Remove files using AWK

>>ls
a.txt
b.txt
c.txt
prabhath_test
a.tt
b.tt

>> ls -l *.tt | awk '{print "rm -r "$9}' | sh
#"rm" is a command, in order to execute, "sh" is used

o/p:

>>ls
a.txt
b.txt
c.txt
prabhath_test



6) AWK - Difference between $0 and $1

>> echo "hello1 hello2 hello3" | awk ' {print $0} ' #$0 prints the whole
hello1 hello2 hello3

>> echo "hello1 hello2 hello3" | awk ' {print $3} ' #$1 prints 1st column
hello3



7) How to print 1st column of a file into another file ?

>>cat test.txt
prabhath kota
lakshmi muvvala
PRABHATH KOTA
LAKSHMI MUVVALA

>> awk '{print $1}' test.txt > output.txt

o/p:

>>cat test.txt
prabhath
lakshmi
PRABHATH
LAKSHMI


No comments:

Post a Comment