awk:相当于 mysql 的“\G”,用于在多行中打印表格数据

awk:相当于 mysql 的“\G”,用于在多行中打印表格数据

是否有与 mysql 查询末尾的“\G”等效的功能,但 awk(或类似功能)会将文本文件中的制表数据打印成多行,并在其旁边显示标题?无论文件中有多少列,都可以这样做。例如:

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

将会变成:

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

答案1

单程:

内容infile

columnA    columnXYZ   columnBLAHBLAH
foo        bar        foobar
blah       blahblah   blahblahblah

内容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
    }   
}

运行脚本:

awk -f script.awk infile

并输出:

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

相关内容