Tabbing the printed fields evenly using awk

后端 未结 3 1737
天涯浪人
天涯浪人 2021-01-27 07:09

i need help using awk. Thanks

i have a file it contains the following

text.txt  
The Hunger Games:Suzanne Collins:1:2:3
Weapon X:Stan Lee:3:4:5
         


        
3条回答
  •  一向
    一向 (楼主)
    2021-01-27 08:05

    The output you show is not tab-separated, it's formatted as a table and for that all you need is:

    $ column -t -s: file
    The Hunger Games  Suzanne Collins  1  2  3
    Weapon X          Stan Lee         3  4  5
    

    If you really wanted it to be tab-separated then that'd be:

    $ tr ':' '\t' < file
    The Hunger Games        Suzanne Collins 1       2       3
    Weapon X        Stan Lee        3       4       5
    

    If you wanted specific fields:

    $ cut -d':' -f 1,4 file | column -t -s:
    The Hunger Games  2
    Weapon X          4
    
    $ cut -d':' -f 1,4 file | tr ':' '\t'
    The Hunger Games        2
    Weapon X        4
    
    $ awk -F':' -v OFS='\t' '{print $1, $4}' file
    The Hunger Games        2
    Weapon X        4
    

    If you don't have column but want tabular output, you can do it all in awk:

    $ cat tst.awk
    BEGIN { FS = ":"; ARGV[ARGC] = ARGV[ARGC-1]; ARGC++ }
    {
        for (i=1; i<=NF; i++)
            if (NR==FNR)
                width[i] = (length($i) > width[i] ? length($i) : width[i])
            else
                printf "%-*s%s", width[i], $i, (i

提交回复
热议问题