Thursday, June 7, 2018

Getting every nth line from file

I had a problem recently where I wanted to extract every 5th line from file and I knew that every 10 lines data points to same 10 keys


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

gave me that




In general if we want to extract every nth line from  file with repeated section of length L

we can just do




awk 'NR%L == n' file.txt 



Assume that we have lines with every section of 5 lines 
awk 'NR%5 == 1' values | awk '{n += $1}; END{print n}'   # sum of every 1st line
awk 'NR%5 == 2' values | awk '{n += $1}; END{print n}'   # sum of every 2nd line
awk 'NR%5 == 3' values | awk '{n += $1}; END{print n}'   # sum of every 3rd line
awk 'NR%5 == 4' values | awk '{n += $1}; END{print n}'   # sum of every 4th line
awk 'NR%5 == 0' values | awk '{n += $1}; END{print n}'   # sum of every 5th line


No comments:

Post a Comment