Take the 2-minute tour ×
Super User is a question and answer site for computer enthusiasts and power users. It's 100% free, no registration required.

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
[...]
share|improve this question
add comment

1 Answer

up vote 4 down vote accepted

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
share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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