Awk: Difference between revisions
From Hackepedia
Jump to navigationJump to search
m added grep in awk example |
m changing from 1st person |
||
Line 1: | Line 1: | ||
It's usually a better idea to use one command instead of using a [[pipe]] to another command, where possible. A common mistake | It's usually a better idea to use one command instead of using a [[pipe]] to another command, where possible. A common mistake: | ||
# grep root /etc/passwd | awk -F: '{print $7}' | # grep root /etc/passwd | awk -F: '{print $7}' | ||
/bin/bash | /bin/bash | ||
which | which can be easily done all in awk: | ||
# awk -F: '/root/ {print $7}' /etc/passwd | # awk -F: '/root/ {print $7}' /etc/passwd | ||
/bin/bash | /bin/bash | ||
Say you wanted to find out how much resident memory [[xfce4]] was using on your system, and it appears most xfce applications start with "xf": | |||
$ ps auwx | awk '/xf/{print $5}' | $ ps auwx | awk '/xf/{print $5}' | ||
15924 | 15924 | ||
Line 19: | Line 19: | ||
If you wanted to use awk to add the results together instead of doing it manually: | |||
$ ps auwx | awk '/xf/{ tot += $5 } END { print tot }' | $ ps auwx | awk '/xf/{ tot += $5 } END { print tot }' | ||
69108 | 69108 | ||
''N.B.'' This can be misleading in the case of programs that use large amounts of shared memory (like java). | ''N.B.'' This can be misleading in the case of programs that use large amounts of shared memory (like java). |
Revision as of 19:29, 15 March 2006
It's usually a better idea to use one command instead of using a pipe to another command, where possible. A common mistake:
# grep root /etc/passwd | awk -F: '{print $7}' /bin/bash
which can be easily done all in awk:
# awk -F: '/root/ {print $7}' /etc/passwd /bin/bash
Say you wanted to find out how much resident memory xfce4 was using on your system, and it appears most xfce applications start with "xf":
$ ps auwx | awk '/xf/{print $5}' 15924 14668 11948 11764 12944 16264 1860
If you wanted to use awk to add the results together instead of doing it manually:
$ ps auwx | awk '/xf/{ tot += $5 } END { print tot }' 69108
N.B. This can be misleading in the case of programs that use large amounts of shared memory (like java).