Monday, December 29, 2008

Awk - formatting fields into columns


One of the common use of awk is to process input files by formatting them, and then output the results in the chosen form.

Input file:
$ cat testresult.txt
NBS Module Status
54670 Reg P
56783 Reg F
56784 Smk P
56744 Reg F

Required output:

NBS Module Status
54670 Reg P
56783 Reg F
56784 Smk P
56744 Reg F


i.e. 1st column<12 spaces>2nd column<10 spaces>3rd column<10 spaces>

Awk solution:

$ awk '
BEGIN {
format=split("12 10 10", arr)
}
{
for(i=1;i<=NF; i++)
printf("%-*s%c", arr[i], $i, (i==NF) ? RS : OFS)
}' testresult.txt


And if we need to change the field separator from space to two tabs, here is a way:

$ awk 'BEGIN{OFS="\t\t"} {$1=$1; print $0}' testresult.txt


NBS Module Status
54670 Reg P
56783 Reg F
56784 Smk P
56744 Reg F

4 comments:

Nathan said...

a sed solution
cat txt | sed -nr 's/(.*) (.*) (.*)/\1\t\2\t\3/g;p'

Jadu Saikia said...

@Nathan, thanks

Christoph said...

column -t < testresult.txt

Jadu Saikia said...

@Christoph, thanks, its a great solution.

© Jadu Saikia www.UNIXCL.com