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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With