Tabbing the printed fields evenly using awk

后端 未结 3 1729
天涯浪人
天涯浪人 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 07:54

    You can pipe awk output to column like this:

    awk -F ':' -v OFS=':' '{print $1, $2 , $3, $4 , $5}' BookDB.txt | column -s ':' -t
    The Hunger Games  Suzanne Collins  1  2  3
    Weapon X          Stan Lee         3  4  5
    
    0 讨论(0)
  • 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<NF?OFS:ORS)
    }
    
    $ awk -f tst.awk file
    The Hunger Games Suzanne Collins 1 2 3
    Weapon X         Stan Lee        3 4 5
    
    0 讨论(0)
  • 2021-01-27 08:09

    Try this to get tab spacings as in your example:

    awk -F: '{if(NR==2)$2="\t"$2;print $1, $2, $3, $4, $5}' OFS="\t" BookDB.txt
    

    Setting : as field seperator and \t as output field seperator. Then for the second line (NR==2), add one extra tab for the second field. Then print the fields.

    Or even simpler (if it is acceptable for you):

    sed "s/:/\t/g" BookDB.txt
    
    0 讨论(0)
提交回复
热议问题