Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extracting last 10 lines of a file that match "foo"

Tags:

grep

bash

unix

I want to write the last ten lines which contain a spesific word such as "foo" in a file to a new text file named for instance boo.txt.

How can I achieve this in the command prompt of a unix terminal?

like image 547
virtue Avatar asked Mar 27 '11 11:03

virtue


1 Answers

You can use grep and tail:

grep "foo" input.txt | tail -n 10 > boo.txt

The default number of lines printed by tail is 10, so you can omit the -n 10 part if you always want that many.

The > redirection will create boo.txt if it didn't exist. If it did exist prior to running this, the file will be truncated (i.e. emptied) first. So boo.txt will contain at most 10 lines of text in any case.

If you wanted to append to boo.txt, you should change the redirection to use >>.

grep "bar" input.txt | tail -n 42 >> boo.txt

You might also be interested in head if you are looking for the first occurrences of the string.

like image 120
Mat Avatar answered Oct 04 '22 22:10

Mat