Learning awk
Print column 1 & 2
ps | awk '{print $1,$2}'
To separate the columns titles you can use "\t" between the numbers:
ps | awk '{print $1"\t"$2}'
By default the field separator for awk is a space, if it's not the case tell awk which one it is by using F for field separator. In the example of /etc/passwd file the separator is semi-colon
awk -F ":" '{print $1}' /etc/passwd
You can also grep:
awk -F ":" '{print $1}' /etc/passwd | grep myservice
To search for every last field in the line, but remove things like comments that are not interesting data use a search command ^
Example in the /etc/shells file. $NF means last field
awk -F "/" '/^\// {print $NF}' /etc/shells
If you want to remove the repeated lines use uniq
awk -F "/" '/^\// {print $NF}' /etc/shells | uniq
Also use sort for a sorted list output:
awk -F "/" '/^\// {print $NF}' /etc/shells | uniq | sort
Print all lines that contain certain words. Example from df command and lines with /dev/vd*:
df | awk
'/\/dev\/vd/ {print $1"\t"$5}'
df
-h
You can do Maths with the columns as well. Example of sum with columns 'Used with Available':
df -h | awk
'/\/dev\/vd/ {print $1"\t"$3 + $4}'
Filter results by the length of the line itself:
awk 'length($0) >
7' /etc/shells
Using AWK as a script in itself
Print last field that contain certain word etc. You need to type the whole path as last field to search the lines with it:
ps -ef | awk '{ if ($NF == "/usr/local/hostguard/bin/hostguard") print $0}'
print $0 means print entire
line
awk
'BEGIN { for (i=1; i<=10; i++) print "The square root of", i,
"is", i*i;}'
Print all the lines that the first character is [a or P]. Capital/lower letter applies:
awk '$1 ~ /^[a,P]/
{print $0}' .bashrc
Depending on the file, sometimes you need to use a different way to get the column. This example use the 'substring function - substr' , print all lines, but removes the first 3 characters / spaces of the line. It will print from 4th character.
awk '{print
substr($0, 4)}' numbered.txt
To get a section of a file, not all lines use 'NR = Number of Records (Line numbers essentially)'
This example will print the range of lines from 7 to 11:
awk 'NR==7, NR==11 {print NR, $0}'
Also take the NR off from print the the lines won't display:
awk 'NR==7, NR==11
{print $0}'
In : Linux
Tags: awk