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
You can use
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.
> 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.
Bad Behavior has blocked 87 access attempts in the last 7 days.