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

新手上路,请多包涵

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

原文由 alwbtc 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 781
2 个回答

通常的方法是使用 grep ,它使用 正则表达式 模式来匹配行:

 grep 'pattern' file

将输出与模式匹配的每一行。如果您只想搜索固定字符串,请使用 grep -F 'pattern' filefgrepgrep -F 的简写。


您也可以使用 sed

 sed -n '/pattern/p' file


awk

 awk '/pattern/' file

原文由 knittl 发布,翻译遵循 CC BY-SA 4.0 许可协议

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

这里有几个例子。假设您想在名为 GPL 的文件中搜索字符串 is

您的示例文件

$ 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;

1. grep

 $ 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

2.awk

 $ 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

3.sed

 $ 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

原文由 user9013730 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题