Awk Printf Command

Embed Size (px)

DESCRIPTION

Awk Printf Command

Citation preview

awk command -----------awk resembles find command in syntaxawk options 'selection_criteria' {action}' file_nameselection_criteria = /pattern/ or address the use awk's build in variable[root@Server1 log]# awk '/root/ {print}' /etc/passwdroot:x:0:0:root:/root:/bin/bashoperator:x:11:0:operator:/root:/sbin/nologin[root@Server1 log]#selection_criteria=/rootaction ={print }file_name = /etc/passwd[root@Server1 log]# awk -F ":" '/root/ {print $1}' /etc/passwdrootoperator[root@Server1 log]#[root@Server1 log]# awk -F ":" '/root/ {print $1,$5}' /etc/passwdroot rootoperator operator[root@Server1 log]#NR = line no NR is build in variable[root@Server1 log]# awk -F ":" 'NR ==3, NR == 6 {print NR,$1}' /etc/passwd3 daemon4 adm5 lp6 sync[root@Server1 log]#printf command-------------printf syntax is similar to Bash, C type printf statement.printf can be useful when specifying data type such as integer, decimal, octal etc. Below are the list of some data types which are available in AWK.%d Decimal%o Octal%x hex%c ASCII number character%s String%f floating number[root@Server1 log]# cat db.txtJones 21 78 84 77Gondrol 23 56 58 45RinRao 25 21 38 37Edwin 25 87 97 95Dayan 24 55 30 47 Print first column values from db.txt file.---------------------------------------------[root@Server1 log]# awk '{printf "%s\n",$1}' db.txtJonesGondrolRinRaoEdwinDayan[root@Server1 log]#If you pass a string to a decimal formatting, it will print just zero instead of that string[root@Server1 log]# awk '{printf "%d\n",$1}' db.txt00000[root@Server1 log]#Padding between columns-----------------------Types of formatting: We can format the columns to specify number of chars each column can use. We have following padding formats available with printf statement.-n = Pad n spaces on right hand side of a column.n = Pad n spaces on left hand side of a column..m = Add zeros on left side.-n.m = Pad n spaces right hand side and add m zeros before that number.n.m = Pad n spaces left hand side and add m zeros before that.[root@Server1 log]# cat db.txtJones 21 78 84 77Gondrol 23 56 58 45RinRao 25 21 38 37Edwin 25 87 97 95Dayan 24 55 30 47[root@Server1 log]# awk '{printf "%d%d%d\n",$2,$3,$4}' db.txt217884235658252138258797245530[root@Server1 log]#With padding 5 spaces on right hand side-----------------------------------------[root@Server1 log]# awk '{printf "%-5d%-5d%-5d\n",$2,$3,$4}' db.txt21 78 8423 56 5825 21 3825 87 9724 55 30[root@Server1 log]#