Wednesday, July 3, 2013

awk tips


1) Search for regular expression "test" in file "my_file" and print first and last field of matched line:
$ awk '/test/ { print $1, $NF }' my_file

2) Regular expression comparison is made by ~ or !~ which result is true or false:

3) Search for lines where first field contains "A" and print that line:
$ awk '$1 ~ /A/' my_file
#or 
awk '{ if ($1 ~ /A/) print }' my_file
#where $1 ~ /A/ means "does first field contains A?"
#print is the same as print $0, thus print whole line = all fields

4) grep -v with awk:
awk \!/text/ my_file
5) filed delimiter different than default space:
gawk -F: '{ print $1 }' /etc/passwd



GNU AWK manual:
http://www.gnu.org/software/gawk/manual/gawk.html



No comments:

Post a Comment