Reputation: 1544
I used awk
to generate the following output
root | /root
bin | /bin
daemon | /sbin
adm | /var/adm
lp | /var/spool/lpd
My awk
query is as follows
head -n 5 /etc/passwd | awk ' BEGIN{ FS=":";OFS=" | "; } { print $1 , $6 } '
I want the output to be displayed in a formatted manner as below
root | /root
bin | /bin
daemon | /sbin
adm | /var/adm
lp | /var/spool/lpd
Is it possible to achieve this using awk
. Also , the code should work on multiple input fields delimited by |
Upvotes: 0
Views: 61
Reputation: 204731
$ cat tst.awk
BEGIN { FS=":"; OFS=" | " }
FNR<=5 {
for (i=1;i<=NF;i++) {
wid[i] = (wid[i] > length($i) ? wid[i] : length($i))
val[NR,i] = $i
}
}
END {
for (rowNr=1; rowNr<=NR; rowNr++) {
printf "%-*s | %-*s\n", wid[1], val[rowNr,1], wid[6], val[rowNr,6]
}
}
The above calculates the max width of each field and then uses that when printing to make sure the fields are aligned properly regardless of the contents of your input file(s).
Upvotes: 0
Reputation: 67567
awk
solution will be using printf
awk -F: '{printf "%-15s | %s\n",$1,$6}' /etc/passwd
note that if you remove -
sign you can right align the userids as well.
Upvotes: 1