在 Linux 上的多个文件中搜索字符串

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

Searching for a string in multiple files on Linux

linuxsearchgrep

提问by Dropout

How to search in multiple files or folders for a string inside a plaintext file?

如何在多个文件或文件夹中搜索纯文本文件中的字符串?

For example I need to find the string "foo" in all files in the folder "/home/thisuser/bar/baz/"

例如,我需要在文件夹“/home/thisuser/bar/baz/”中的所有文件中找到字符串“foo”

采纳答案by Dropout

You need to have read privileges on the files you will be searching in. If you do have them, then simply use

您需要对将要搜索的文件具有读取权限。如果您确实拥有它们,则只需使用

grep -r "foo" /home/thisuser/bar/baz/*

to search in a certain folder or

在某个文件夹中搜索或

grep "foo" /home/thisuser/bar/baz/somefile.txt

if you need to search in a specific file, in this case "somefile.txt". Basically the syntax is

如果您需要在特定文件中搜索,在本例中为“somefile.txt”。基本上语法是

grep [options] [searched string] [path]
// -r is an option which states that it will use recursive search

Another useful options are "-n" to show on which line in which file the string is located, "-i" to ignore case, "-s" to suppress some messages like "can't read file" or "not found" and "-I" to ignore binary files.

另一个有用的选项是“-n”显示字符串位于哪个文件的哪一行,“-i”忽略大小写,“-s”抑制一些消息,如“无法读取文件”或“未找到”和“-I”忽略二进制文件。

If you use

如果你使用

grep -rnisI "foo" /home/thisuser/bar/baz/*

you will exactly know where to look.

你会确切地知道在哪里看。

回答by abhishek verma

Use

grep -r "foo" /home/thisuser/bar/baz/