Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
619 views
in Technique[技术] by (71.8m points)

printing - print every nth line into a row using gawk

I have a very huge file in which I need to obtain every nth line and print it into a row.

My data:

1      937  4.320194
2      667  4.913314
3      934  1.783326
4      940  -0.299312
5      939  2.309559
6      936  3.229496
7      611  -1.41808
8      608  -1.154019
9      606  2.159683
10     549  0.767828

I want my data to look like this:

1      937  4.320194
3      934  1.783326
5      939  2.309559
7      611  -1.41808
9      606  2.159683

This is of course an example, I want every 10th line for my huge data file. I tried this so far:

 NF == 6 {
     if(NR%10) {print;}
     }
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

To print every second line, starting with the first:

awk 'NR%2==1' file.txt

To print every tenth line, starting with the tenth line:

awk 'NR%10==0' file.txt

To use this in a script, add the following to a file called script.awk:

BEGIN {
    print "Processing file"
}

NR%10==0

END {
    print "Finished processing"
}

Then execute:

awk -f script.awk file.txt

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...