Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

automatic text formatting with printf (basing on maxlength of each column) 1

Status
Not open for further replies.

w5000

Technical User
Nov 24, 2010
223
PL
hi,
the input file has n columns delimeted with "|" like on example below.
how to find max lenght for each column and use it later for printf formatting the input file?

awk '{ printf "%-[highlight #EF2929]max1[/highlight]s %-[highlight #EF2929]max2[/highlight]s %-[highlight #EF2929]max3[/highlight]s %-s\n", $1, $2, $3, $4 }' ....

for testing
# echo -e "121|234234|5345|2342342342432423\n1|2342|2|2342\n234|23|343|34214222"
121|234234|5345|2342342342432423
1|2342|2|2342
234|23|343|34214222

thank you in advance

 
Hi

Not aware of much possibilities for improvement. I would do it with usual 2 passes with a [tt]for[/tt] look in each :
Code:
awk -F '|' '
    FNR [teal]==[/teal] NR [teal]{[/teal]
        [b]for[/b] [teal]([/teal]i [teal]=[/teal] [purple]1[/purple][teal];[/teal] i [teal]<=[/teal] NF[teal];[/teal] i[teal]++)[/teal]
            [b]if[/b] [teal]([/teal]m[teal][[/teal]i[teal]] <[/teal] [b]length[/b][teal]([/teal][navy]$i[/navy][teal]))[/teal]
                m[teal][[/teal]i[teal]] =[/teal] [b]length[/b][teal]([/teal][navy]$i[/navy][teal])[/teal]
        [b]next[/b]
    [teal]}[/teal]

    [teal]{[/teal]
        [b]for[/b] [teal]([/teal]i [teal]=[/teal] [purple]1[/purple][teal];[/teal] i [teal]<=[/teal] NF[teal];[/teal] i[teal]++)[/teal]
            [b]printf[/b] [i][green]"%-*s%s"[/green][/i][teal],[/teal] m[teal][[/teal]i[teal]],[/teal] [navy]$i[/navy][teal],[/teal] i [teal]<[/teal] NF [teal]?[/teal] [i][green]" | "[/green][/i] [teal]:[/teal] ORS
    [teal]}[/teal]
' /path/to/input /path/to/input


Feherke.
feherke.github.io
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top