Extracting the last 10 lines of a file matching "foo",

I want to write the last ten lines containing a spesific word in a file, such as "foo", into a new text file called instance boo.txt .

How can I achieve this on a unix terminal command line?

+7
source share
2 answers

You can use grep and tail :

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

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

Redirecting > will create boo.txt if it does not exist. If it existed before its launch, the file will first be truncated (i.e. empty). Thus, boo.txt will contain no more than 10 lines of text anyway.

If you want to add to boo.txt , you must change the redirection to use >> .

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

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

+18
source
 grep foo /path/to/input/file | tail > boo.txt 
+1
source

All Articles