如何在linux中查找包含字符串的行

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

How to find lines containing a string in linux

linuxstringfilesearch

提问by alwbtc

I have a file in Linux, I would like to diplay lines which contain a specific string in that file, how to do this?

我在 Linux 中有一个文件,我想显示该文件中包含特定字符串的行,该怎么做?

采纳答案by knittl

The usual way to do this is with grep

通常的方法是使用 grep

grep 'pattern' file

回答by Brian Agnew

The grepfamily of commands (incl egrep, fgrep) is the usual solution for this.

所述的grep命令的家族(包括egrep的,fgrep一样)是用于这个通常的解决方法。

$ grep pattern filename

If you're searching source code, then ackmay be a better bet. It'll search subdirectories automatically and avoid files you'd normally not search (objects, SCM directories etc.)

如果您正在搜索源代码,那么ack可能是更好的选择。它将自动搜索子目录并避免您通常不会搜索的文件(对象、SCM 目录等)

回答by deFreitas

/tmp/myfile

/tmp/我的文件

first line text
wanted text
other text

the command

命令

$ grep -n "wanted text" /tmp/myfile | awk -F  ":" '{print }'
2

回答by Sabrina

Besides grep, you can also use other utilities such as awkor sed

此外grep,您还可以使用其他实用程序,例如awksed

Here is a few examples. Let say you want to search for a string isin the file named GPL.

这里有几个例子。假设您要is在名为GPL.

Your sample file

您的示例文件

user@linux:~$ cat -n GPL 
     1    The GNU General Public License is a free, copyleft license for
     2    The licenses for most software and other practical works are designed
     3  the GNU General Public License is intended to guarantee your freedom to
     4  GNU General Public License for most of our software;
user@linux:~$ 

1. grep

1.grep

user@linux:~$ grep is GPL 
  The GNU General Public License is a free, copyleft license for
the GNU General Public License is intended to guarantee your freedom to
user@linux:~$ 

2. awk

2.awk

user@linux:~$ awk /is/ GPL 
  The GNU General Public License is a free, copyleft license for
the GNU General Public License is intended to guarantee your freedom to
user@linux:~$ 

3. sed

3. sed

user@linux:~$ sed -n '/is/p' GPL
  The GNU General Public License is a free, copyleft license for
the GNU General Public License is intended to guarantee your freedom to
user@linux:~$ 

Hope this helps

希望这可以帮助