Linux 终端命令查找包含特定单词的行?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9074353/
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-08-06 04:18:00  来源:igfitidea点击:

Terminal command to find lines containing a specific word?

linuxtextterminal

提问by willykao

I was just wondering what command i need to put into the terminal to read a text file, eliminate all lines that do not contain a certain keyword, and then print those lines onto a new file. for example, the keyword is "system". I want to be able to print all lines that contain system onto a new separate file. Thanks

我只是想知道我需要在终端中输入什么命令来读取文本文件,删除所有不包含某个关键字的行,然后将这些行打印到一个新文件上。例如,关键字是“系统”。我希望能够将包含 system 的所有行打印到一个新的单独文件上。谢谢

采纳答案by Eric B.

grepis your friend.

grep是你的朋友。

For example, you can do:

例如,您可以执行以下操作:

grep system <filename> > systemlines.out

man grep and you can get additional useful info as well (ex: line numbers, 1+ lines prior, 1+lines after, negation - ie: all lines that do not contain grep, etc...)

man grep 并且您还可以获得其他有用的信息(例如:行号、1+ 行之前、1+ 行之后、否定 - 即:所有不包含 grep 的行等...)

If you are running Windows, you can either install cygwinor you can find a win32 binary for grep as well.

如果您运行的是 Windows,您可以安装cygwin,也可以为 grep 找到一个 win32 二进制文件。

回答by Craig Mc

grep "system" filename > new-filename

grep“系统”文件名>新文件名

You might want to make it a bit cleverer to not include lines with words like "dysystemic", but it's a good place to start.

您可能想让它更聪明一点,不包含带有“dysystemic”之类的词的行,但这是一个很好的起点。

回答by Balaswamy Vaddeman

below grepcommand will solve ur problem

下面的grep命令将解决你的问题

grep -i yourword filename1 > filename2

with -i for case insensitiveness

with -i for case insensitiveness

without -i for case sensitiveness

without -i for case sensitiveness

to learn how grep works on ur server ,refer to man page on ur server by the following command

要了解 grep 如何在您的服务器上工作,请通过以下命令参考您的服务器上的手册页

man grep

回答by Jonathon Reinhart

grep '\<system\>'

Will search for lines that contain the wordsystem, and not system as a substring.

将搜索包含单词system 而不是 system 作为子字符串的行。