AWK
pattern {action}
BEGIN and END patterns in the AWK
BEGIN { print “BEGIN” }
{ print }
END { print “END” }
# cat textfile.txt
Ashish 123
Ashi 456
Ash 789
A 000
# awk '{print $1}' textfile.txt
Ashish
Ashi
Ash
A
# awk '{print $2}' textfile.txt
123
456
789
000
# awk '{print $2,$1}' textfile.txt
123 Ashish
456 Ashi
789 Ash
000 A
If the file is seperated with some delimeter, then we make use of -F for awk.
In the below example, the input file is using the pipe ( | ) as delimiter.
# cat textfile.txt
Ashish|123
Ashi|456
Ash|789
A|000
Ashish|007
# awk -F\| '{print $1}' textfile.txt
Ashish
Ashi
Ash
A
Ashish
# awk -F\| '{print $2}' textfile.txt
123
456
789
000
007
# awk -F\| '{print $2,$1}' textfile.txt
123 Ashish
456 Ashi
789 Ash
000 A
007 Ashish
# awk -F\| '$1=="Ashish"' textfile.txt
Ashish|123
Ashish|007
# awk -F\| '$1=="Ashish"{print $1}' textfile.txt
Ashish
Ashish
# awk -F\| '$1=="Ashish"{print $2}' textfile.txt
123
007
To print the lines which does not contain the pattern Ashish:
# awk '!/Ashish/' textfile.txt
Ashi|456
Ash|789
A|000
To print the records whose amount is greater then zero:
# awk -F\| '$2>0' textfile.txt
Ashish|123
Ashi|456
Ash|789
Ashish|007
To print the Ashish record only if it the first record:
# awk 'NR==1 && /Ashish/' textfile.txt
Ashish|123
To print all Ashish record whose amount is greater then zero:
# awk -F\| '/Ashish/ && $2>0' textfile.txt
Ashish|123
Ashish|007
# awk -F\| '/Ashish/ && $2>0' textfile.txt
Ashish|123
Ashish|007
In some cases we don't know how many fields (columns) are there in the file, we can make use of special variable called NF (Number of fields).
we can print the last field using $NF and last before column as $(NF-1).
| awk Variable | Meaning |
| FILENAME | Name of current input file |
| RS | Input record separator character (Default is new line) |
| OFS | Output field separator string (Blank is default) |
| ORS | Output record separator string (Default is new line) |
| NF | Number of input record |
| NR | Number of fields in input record |
| OFMT | Output format of number |
| FS | Field separator character (Blank & tab is default) |
Comments
Post a Comment