Difference between revisions of "Awk"
From Noah.org
Jump to navigationJump to searchLine 24: | Line 24: | ||
want a real scripting language. Average of column 3: | want a real scripting language. Average of column 3: | ||
awk '{total+=$3;count++;}END{print total/count;}' file | awk '{total+=$3;count++;}END{print total/count;}' file | ||
+ | |||
+ | === show CLI usage statistics === | ||
+ | |||
+ | This is probably useless, but interesting. This counts and sorts the commands as seen by the Bash CLI history. | ||
+ | |||
+ | <pre> | ||
+ | history | awk {'print $2'} | sort | uniq -c | sort -k1 -n | ||
+ | </pre> | ||
+ | |||
+ | Gives something like this: | ||
+ | |||
+ | <pre> | ||
+ | ... | ||
+ | 65 chmod | ||
+ | 71 svn | ||
+ | 84 df | ||
+ | 116 rm | ||
+ | 132 sudo | ||
+ | 390 ls | ||
+ | 396 cd | ||
+ | 631 vim | ||
+ | 1202 exit | ||
+ | 1359 mutt | ||
+ | </pre< |
Revision as of 22:10, 5 May 2008
About the most I ever use awk for is to print fields I want from a delimited file. For example, to print field #2 from a file (assuming white space between columns):
awk '{print $2;}' file
If the fields have other delimiters such as '/' then use the -F option to set the delimiter. For example to print the first directory from a list of file paths use this:
awk -F '/' '{print $1;}' file
So if I had a list of filenames such as:
subversion-1.3.2/README subversion-1.3.2/configure.in subversion-1.3.2/TRANSLATING subversion-1.3.2/subversion subversion-1.3.2/subversion/libsvn_fs_base subversion-1.3.2/subversion/libsvn_fs_base/bdb
Running that list through the example would produce
subversion-1.3.2 subversion-1.3.2 subversion-1.3.2 subversion-1.3.2 subversion-1.3.2 subversion-1.3.2
Once you get much more complicated than this then you probably want a real scripting language. Average of column 3:
awk '{total+=$3;count++;}END{print total/count;}' file
show CLI usage statistics
This is probably useless, but interesting. This counts and sorts the commands as seen by the Bash CLI history.
history | awk {'print $2'} | sort | uniq -c | sort -k1 -n
Gives something like this:
... 65 chmod 71 svn 84 df 116 rm 132 sudo 390 ls 396 cd 631 vim 1202 exit 1359 mutt </pre<