AWK 101
awk is a tool to process text, line by line.
Variable
$0
means whole line, $1
means the first column, NF
means the last column, ‘NR’ means nubmer of row. etc.
- List process name
ps | awk '{print $1}'
Seperator
use :
as seperator (default is space), print out the first, 6th and 7th column. use Tab
between them.
awk -F ":" '{print $1"\t"$6"\t"$7}' /etc/passwd
Change Seperator as output
use :
as seperator, output use Tab
as seperator, print out the first, 6th and 7th column. (Use comma in between, so they are columns, and awk can insert Tab
in between.
awk 'BEGIN{FS=":"; OFS="\t"} {print $1, $6, $7}' /etc/passwd
Print last column
search the line start with ‘/’, use ‘/’ as seperator, print out the last column.
awk -F "/" '/^\// {print $NF}' /etc/shells
function
- print lines which is longer than 7
awk 'length($0) > 7' /etc/shells
- print all bash process
awk 'length($0) > 7' /etc/shells
- substring
Comments