AWK tutorial: awk [-F] print example

Linux AWK print function is one of the most commonly used functions, so it’s important to understand it.

awk print $0

➜ echo "test" | awk '{print}'
➜ echo "test" | awk '{print $0}'

Running results as above:

awk '{print}' == awk '{print $0}'
  • $0 : Represents the entire current line
  • $1 : First field per line
➜  awk echo "test" | awk '{print $1}'

test

use -F specifies a delimiter

➜ echo "a:B:C:CS:DDDD" | awk -F":" '{print $2}' 
a   :   B   :   C   :   CS   :   DDDD
$1      $2      $3      $4        $5

continuous output of $2 and $5

➜ echo "a:B:C:CS:DDDD" | awk -F":" '{print $2 $5}'

space output of $2 and $5

ylspiritdeMacBook-Pro:awk ylspirit$ echo "a:B:C:CS:DDDD" | awk -F":" '{print $2,$5}'
B DDDD

custom output of $2 and $5

ylspiritdeMacBook-Pro:awk ylspirit$ echo "a:B:C:CS:DDDD" | awk -F":" '{print $2 ":" $5}'
B:DDDD
ylspiritdeMacBook-Pro:awk ylspirit$ echo "a:B:C:CS:DDDD" | awk -F":" '{print $2 "#" $5}'
B#DDDD

print specific columns

➜ awk '{print $2}' test.txt

use NR to print specific rows

➜ awk 'NR==2{print}' test.txt

use NF to print the number of fields in the current record

➜ awk 'NF==2 {print $0}' test-1.txt

print line number per line

➜  awk '{print NR, $0}' test-1.txt
linux awk print line number per line

use OFS output specific format

ylspiritdeMacBook-Pro:awk ylspirit$ echo "a:B:C:CS:DDDD" | awk -F":" '{print $2,$5}' OFS="|"
B|DDDD

awk print last field

➜ awk '{print $NF}' test2.txt
linux awk print last field


Add a Comment

Your email address will not be published. Required fields are marked *