File Formatting : Confusion using awk NR Variable

2019-07-06 00:04发布

I am new to awk programming and little confused about the use of NR variable ..

My code is ...

awk 'BEGIN {k=NR;}{printf("%s %s %s %s\n",$k,$(k+1),$(k+2),$(k+3))}' auth_data

$ cat auth_data

6262 6530 6661 3162 6364 6264 6561 3430 3033 3332 6536 3139 6230 6261 61
30 3637 0A00 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000
0000 0000 0000 

Output :

6262 6530 6661 3162 6364 6264 6561 3430 3033 3332 6536 3139 6230 6261 6130
3637 0A00 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000
0000 0000  6262 6530 6661

But what I want is that output should be in this format :

  6262 6530 6661 3162 6364 6264 6561 3430
  3033 3332 6536 3139 6230 6261 6130 3637 
  0A00 0000 0000 0000 0000 0000 0000 0000
  0000 0000 0000 0000 0000 0000 0000 0000 

1条回答
太酷不给撩
2楼-- · 2019-07-06 00:41

I guess what you are looking for is NF, not NR.

from Manpage:

NR The total number of input records seen so far.

NR is actual line number, but in this problem, you want to do some trick on field idx, not lines.

Also, I thought your input data should be in one line in file 'auth_data', right?

if it is so, you could try

awk '{for(i=1;i<=NF;i++)if(i%8==0)print $i;else printf $i" "}' auth_data

check the test below:

kent$  echo "6262 6530 6661 3162 6364 6264 6561 3430 3033 3332 6536 3139 6230 6261 6130 3637 0A00 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000"|\
awk '{for(i=1;i<=NF;i++)if(i%8==0)print $i;else printf $i" "}'
    6262 6530 6661 3162 6364 6264 6561 3430
    3033 3332 6536 3139 6230 6261 6130 3637
    0A00 0000 0000 0000 0000 0000 0000 0000
    0000 0000 0000 0000 0000 0000 0000 0000

And back to the problem, if you just want to do the formatting, xargs is enough. see below:

kent$  echo "6262 6530 6661 3162 6364 6264 6561 3430 3033\
        3332 6536 3139 6230 6261\
        6130 3637 0A00 0000 0000 \
        0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000"|xargs -n8

output:

6262 6530 6661 3162 6364 6264 6561 3430
3033 3332 6536 3139 6230 6261 6130 3637
0A00 0000 0000 0000 0000 0000 0000 0000
0000 0000 0000 0000 0000 0000 0000 0000

you can cat yourFile|xargs -n8 or xargs -n8 -a yourfile

查看更多
登录 后发表回答