Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Copy last line from multiple files into a single file

Tags:

shell

unix

tail

I have a number of files in a directory. I would like to go through the directory, and put the last line of each file into a single new file. IE, this new file should contain the last line of every file in the directory. I tried using

tail -n 1 | cat > newfile.txt

but that inserted the source file name between each line. I tried writing a shell script also, but the only thing it did successfully is create the destination file and then run indefinitely without ever adding data. What is the proper way to do this? Any help is much appreciated.

like image 714
ddn Avatar asked Sep 20 '25 01:09

ddn


1 Answers

Use find:

find . -type f -exec tail -n1 {} >> newfile.txt \;

Or if you don't want to traverse subdirectories:

find . -depth 1 -type f -exec tail -n1 {} >> newfile.txt \;
like image 81
pb2q Avatar answered Sep 23 '25 11:09

pb2q