开发者

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

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 pro开发者_StackOverflowmpt 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.


grep foo /path/to/input/file | tail > boo.txt
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜