Search code examples
awksedgrepcut

How to get text file content to table using awk,sed,grep or cut in linux terminal prompt


cat raw.txt

Name country IP Cost  
sam us 10.10.10.10 $250  
jack India 10.10.10.12 $190  
joy Australia 10.10.10.13 $230  
christ canada 10.10.10.15 $190  
jackson africa 10.10.10.20 $230

I need to output like a table list four column and four row, i.e Name Country IP Cost

http://res.cloudinary.com/dzy8bgton/image/upload/v1413617325/Screenshot_from_2014-10-18_12_35_11_h6wjsu.png

please anyone can help me out.


Solution

  • Here's an old school answer :-)

    #!/bin/sh
    # use tbl|nroff to make an ASCII table
    # use sed to change multiple spaces into a  single tab for tbl(1)
    sed 's/  */\t/g' < raw.txt | awk '
    BEGIN {
        print ".TS" # beginning of table
        print "allbox;" # allbox format
        print "c s s s" # Table name format - centered and spanning 4 columns
        print "lb lb lb lb" # bold column headers
        print "l l l l." # table with 4 left justified columns. "." means repeat for next line
        print "My Table" # Table name
    }
    {print} # print each line of 4 values
    END {
        print ".TE" # end of table
    }' | tbl | nroff -Tdumb
    

    which generates

    ┌─────────────────────────────────────────┐
    │                My Table                 │
    ├────────┬───────────┬─────────────┬──────┤
    │Name    │ country   │ IP          │ Cost │
    ├────────┼───────────┼─────────────┼──────┤
    │sam     │ us        │ 10.10.10.10 │ $250 │
    ├────────┼───────────┼─────────────┼──────┤
    │jack    │ India     │ 10.10.10.12 │ $190 │
    ├────────┼───────────┼─────────────┼──────┤
    │joy     │ Australia │ 10.10.10.13 │ $230 │
    ├────────┼───────────┼─────────────┼──────┤
    │christ  │ canada    │ 10.10.10.15 │ $190 │
    ├────────┼───────────┼─────────────┼──────┤
    │jackson │ africa    │ 10.10.10.20 │ $230 │
    └────────┴───────────┴─────────────┴──────┘