简体   繁体   中英

awk:How return number of columns by awk?

Data source:

a b c d

Expect:

$1 $2 $3 $4
a  b  c  d

I try to echo 'abc d'| awk 'END {for(i=1;i<=NF;i++) printf("$%d\\t",i)}' echo 'abc d'| awk 'END {for(i=1;i<=NF;i++) printf("$%d\\t",i)}' (but fail)

$ echo 'a b c d' |
    awk 'FNR==1{for (i=1;i<=NF;i++) printf "$%d%s", i, (i<NF ? OFS : ORS)} 1'
$1 $2 $3 $4
a b c d

$ echo 'a b c d' |
    awk 'FNR==1{for (i=1;i<=NF;i++) printf "$%d%s", i, (i<NF ? OFS : ORS)} 1' |
    column -t
$1  $2  $3  $4
a   b   c   d

Read Effective Awk Programming, 4th Edition, by Arnold Robbins - trying to do this in the END section and other things in your script indicate you are missing the fundamentals of awk.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM