print every nth line into a row using gawk

旧街凉风 提交于 2019-11-29 21:34:58

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

With sed, you can do a lot of variations on this quite easily with the first~step command. For instance:

# Odd lines
sed -n 1~2p file
# Every tenth line (10, 20, 30, ...)
sed -n 10~10p file
# Every tenth line (1, 11, 21, ...)
sed -n 1~10p file
# First plus every tenth (1, 10, 20, 30, ...)
sed -n -e 1p -e 10~10p file

Piece of cake: cat test.txt | awk 'NR % 10 == 1'

It's not (g)awk, but it'll work:

cat myfile | grep ^[[:digit:]]*0[[:blank:]] should do the trick.

Doing it directly in command Prompt (Windows).

Put the gawk.exe file in the folder where the file is and start a command Prompt in the folder, and write

gawk "NR%n==x" oldfile.txt>newfile.txt

n is every n'th line you want to print and x is the starting line.

E.g n=10 and x=1, printing line 1,11,21,31,41......end line from the original file into the new file.

E.g n=20 and x=5, printing line 5,25,45,65......end line from the original file into the new file.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!