It can all be done in awk
with two rules. You can handle outputting the first part of the heading in the second rule, saving all fields in the array a[]
, and then the second rule will output the needed elements of a[]
and the current fields in the format you specify. For example:
Set '|'
as the field separator wtih -F'|'
, and
awk -F'|' '
FNR > 1 { # record (line) > 1
if (FNR == 2) # if line is 2
print "| " $2 # finish heading row
for (i=3;i<=NF;i+=2) # loop from 3rd field by 2
printf (i==3?"|":"") "%s: %s ",a[i],$i # output info
for (i=4;i<=NF;i+=2) # loop from 4th field by 2
printf (i==4?"
|":"") "%s: %s ",a[i],$i # output info
print "" # tidy up with newline
delete a # clear the array
for (i=1; i<=NF; i++) # fill array with current fields
a[i]=$i
next # skip to next line
}
{
printf "%s", $2 # output 1st part of heading
for (i=1; i<=NF; i++) # fill array with current fields
a[i]=$i
}
' file
The order of execution is a bit backwards. The rule handling the first line is actually the last rule above between the bottom {...}
the top rule handles the second line on.
Example Use/Output
With your input in the file named file
, you can just select-copy the above and middle-mouse paste into an xterm with the current directory containing file
to test, e.g.:
awk -F'|' '
> FNR > 1 { # record (line) > 1
> if (FNR == 2) # if line is 2
> print "| " $2 # finish heading row
> for (i=3;i<=NF;i+=2) # loop from 3rd field by 2
> printf (i==3?"|":"") "%s: %s ",a[i],$i # output info
> for (i=4;i<=NF;i+=2) # loop from 4th field by 2
> printf (i==4?"
|":"") "%s: %s ",a[i],$i # output info
> print "" # tidy up with newline
> delete a # clear the array
> for (i=1; i<=NF; i++) # fill array with current fields
> a[i]=$i
> next # skip to next line
> }
> {
> printf "%s", $2 # output 1st part of heading
> for (i=1; i<=NF; i++) # fill array with current fields
> a[i]=$i
> }
> ' file
place_loc| AAAAA_AAA
|CATA: 1234 CATA1: 12
|CATB: 123 CATB1: 1234
The output above is:
place_loc| AAAAA_AAA
|CATA: 1234 CATA1: 12
|CATB: 123 CATB1: 1234
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…