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:
a sed solution
cat txt | sed -nr 's/(.*) (.*) (.*)/\1\t\2\t\3/g;p'
@Nathan, thanks
column -t < testresult.txt
@Christoph, thanks, its a great solution.
Post a Comment