Extracting last "n" lines of a file that match “foo”
I want to write the last ten lines which contain a specific word such as “foo” in a file to a new text file named for instance boo.txt
.
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.