NR: Number of records (rows) read so far.NF: Number of fields (columns) in the current record (row).IFS: Input field seperator.OFS: Output field seperator.The default input field separator is " ". A different field separator
can be specified by using the -F option.
cat /etc/passwd | awk -F: '{print $1}'
The default output field separator is " ". A different field separator
can be specified by using OFS. In the example below, $1=$1 forces awk
to rebuild the entire record using the current value of OFS. See 1.
echo "All that is gold does not glitter" | awk '{OFS="-"; $1=$1; print $0}'
echo "All that is gold does not glitter" | awk -v OFS="-" '{$1=$1; print $0}'
ls -l | awk 'BEGIN{sum=0}{sum += $5}END{print sum}'
The following also works because awk variables are automatically initialized to zero.
ls -l | awk '{sum += $5}END{print sum}'
Use the awk variable NR.
cat /etc/passwd | awk '{print NR, $0}'
Use the awk variable NF.
ls -l | awk '{print NF}'
cat /etc/passwd | awk -F: '{print NF}'
Use the awk variable NF with a $ sign to dereference it.
ls -l | awk '{print $NF}'
cat /etc/passwd | awk -F: '{print $NF}'
Use the awk variable NF with a $ sign to dereference it.
ls -l | awk '{print $(NF-1)}'
cat /etc/passwd | awk -F: '{print $(NF-1)}'
This is the same as wc -l.
cat /etc/passwd | awk 'END{print NR}'