Tuesday, October 25, 2011

One liner - awk, gawk

Print specific columns
awk '{ print $5, $1, $2 }' fileName

Print specific columns separated by : delimeter
awk -F':' '{ print $5, $1, $2 }' fileName

Count number of words in a line
$awk '{print NF}' fileName


Maximum in first column of a file
$awk '$1 > max { max=$1;}; END { print max }' fileName 


Minimum in third column of a file
$awk 'NR==1 { min=$3 } $3 < min { min=$3;}; END { print min }' fileName


Combining columns of two files
$cat file1
one two three
one two three
one two three



$cat file2
four five six
four five six
four five six



$pr -m -t -s\ file1 file2 | gawk '{print $4,$5,$6,$1}'
four five six
four five six one
four five six one



Break a line into multiple lines
$cat fileName
1 2 3 4 5 6 7 8 9 10 11 12



$awk -F' ' '{for(i=1;i<=NF;i++){printf("%s%s",$i,i%3?" ":"\n")}}' fileName
1 2 3
4 5 6
7 8 9
10 11 12


Insert newline after every 2 lines
$cat fileName
FR 24
AA 33
EE 34
EE 46
BE 30
AA 31
DE 90
AL 10

$awk '!( NR % 3 ) {$0 = $0"\n"} 1' fileName
FR 24
AA 33

EE 34
EE 46

BE 30
AA 31

DE 90
AL 10

No comments:

Post a Comment