Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get N'th line of multiple files in linux

Tags:

linux

echo

csv

sed

awk

The task I'm trying to accomplish is, I have this kind of files:

test1.csv test2.csv test3.csv etc...

And I want to get 3'rd line of every file. Right now, I can get 3'rd lines using awk, or sed like

echo | awk 'FNR == 3 { print; exit }' test1.csv >> last_file.csv or using sed or tail.

But when I try to do this on multiple files, It cannot get the lines. I want to do like this,

echo | awk 'FNR == 3 { print; exit }' test*.csv >> last_file.csv

How can I achieve this?

Thank you.

like image 451
mau5 Avatar asked Aug 06 '15 00:08

mau5


2 Answers

Get rid of the useless echo, the incorrect exit and the redundant print:

awk 'FNR == 3' test*.csv
like image 138
Ed Morton Avatar answered Oct 12 '22 00:10

Ed Morton


You should use

awk 'FNR == 3 { print; nextfile }' test*.csv >> last_file.csv

The problem is that when you use exit, it stops awk from processing input completely. The nextfile tells awk to stop processing the current file and go to the next file. The echo command as you are using it is not necessary.

Read more here:

http://www.gnu.org/software/gawk/manual/html_node/Nextfile-Statement.html

like image 37
bkmoney Avatar answered Oct 12 '22 00:10

bkmoney