2

Is there an equivalent to mysql's "\G" at the end of the query but awk (or similar) that will to print tabulated data from a text file in multiple lines with the header next to it? Something that will do no matter how many columns are in the file. For example:

columnA    columnXYZ   columnBLAHBLAH
foo        bar        foobar
blah       blahblah   blahblahblah
[...]

Will turn into:

************ 1. row ***********
       columnA: foo
     columnXYZ: bar
columnBLAHBLAH: foobar
************ 2. row ***********
       columnA: blah
     columnXYZ: blahblah
columnBLAHBLAH: blahblahblah
[...]
4

One way:

Content of infile:

columnA    columnXYZ   columnBLAHBLAH
foo        bar        foobar
blah       blahblah   blahblahblah

Content of script.awk:

FNR == 1 { 
    split( $0, header )
}

FNR > 1 { 
    printf "************ %d. row ************\n", FNR-1
    for ( i = 1; i <= NF; i++ ) { 
        printf "%14s: %-14s\n", header[ i ], $i
    }   
}

Run the script:

awk -f script.awk infile

And output:

************ 1. row ************
       columnA: foo           
     columnXYZ: bar           
columnBLAHBLAH: foobar        
************ 2. row ************
       columnA: blah                                                                                                                                                                                                                         
     columnXYZ: blahblah                                                                                                                                                                                                                     
columnBLAHBLAH: blahblahblah

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.