0

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 |

3 Answers 3

2

try piping your awk result to column:

awk 'whatever'|column -t
Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

0
$ 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).

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.