Get N'th line from multiple files in Linux

The task I am trying to accomplish, I have files like this:

test1.csv test2.csv test3.csv etc.

And I want to get the 3'rd line of each 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 with sed or tail.

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

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

How can I achieve this?

Thank.

+3


source to share


4 answers


Get rid of the useless echo

, wrong exit

and redundant print

:



awk 'FNR == 3' test*.csv

      

+9


source


You must use

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

      

The problem is, when used, exit

it completely disables awk from processing input. nextfile

tells awk to stop processing the current file and move on to the next file. The command echo

, since you are using it, is not required.



More details here:

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

+2


source


This might work for you (GNU sed):

sed -sn 3p test*.csv >> last_file.csv

      

+1


source


If you want to do this in all files in directories and its subdirectories and so on.

shopt -s globstar
awk 'FNR == 3' **/test*.csv

      

0


source







All Articles