bash 提取与“foo”匹配的文件的最后 10 行

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5448882/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 20:20:17  来源:igfitidea点击:

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

bashunixgrep

提问by virtue

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.

我想将文件中包含特定单词(例如“foo”)的最后十行写入名为 example 的新文本文件boo.txt

How can I achieve this in the command prompt of a unix terminal?

如何在 unix 终端的命令提示符下实现这一点?

回答by Mat

You can use grepand tail:

您可以使用greptail

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

The default number of lines printed by tailis 10, so you can omit the -n 10part if you always want that many.

打印的默认行数tail是 10,所以-n 10如果你总是想要那么多,你可以省略这部分。

The >redirection will create boo.txtif it didn't exist. If it did exist prior to running this, the file will be truncated (i.e. emptied) first. So boo.txtwill contain at most 10 lines of text in any case.

如果>重定向boo.txt不存在,则会创建。如果它在运行之前确实存在,则该文件将首先被截断(即清空)。所以boo.txt无论如何都将包含最多 10 行文本。

If you wanted to append to boo.txt, you should change the redirection to use >>.

如果您想附加到boo.txt,您应该将重定向更改为使用>>

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

You might also be interested in headif you are looking for the first occurrences of the string.

head如果您正在寻找字符串的第一次出现,您可能也会感兴趣。

回答by sarnold

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