Difference between revisions of "Awk"
Line 31: | Line 31: | ||
<pre> | <pre> | ||
history | awk {'print $2'} | sort | uniq -c | sort -k1 -n | history | awk {'print $2'} | sort | uniq -c | sort -k1 -n | ||
+ | </pre> | ||
+ | |||
+ | If you have $HISTTIMEFORMAT set then use this instead: | ||
+ | |||
+ | <pre> | ||
+ | history | awk {'print $3'} | sort | uniq -c | sort -k1 -n | ||
</pre> | </pre> | ||
Latest revision as of 10:11, 1 October 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
If you have $HISTTIMEFORMAT set then use this instead:
history | awk {'print $3'} | 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
Kill All by grep
This is similar to `killall` except that it matches a process by pattern -- this can be more dangerous.
alias ka='kill -9 `ps auxww | grep -i $1 | sed \$d`'