查找名称中包含字符串的所有文件

时间:2012-07-04 12:19:37

标签: linux unix command-line locate

我一直在搜索一个命令,该命令将返回当前目录中包含文件名中字符串的文件。我看过locatefind命令可以找到以first_word*开头或以*.jpg结尾的文件。

如何返回文件名中包含字符串的文件列表?

例如,如果2012-06-04-touch-multiple-files-in-linux.markdown是当前目录中的文件。

如何归还此文件以及包含字符串touch的其他文件?使用find '/touch/'

等命令

8 个答案:

答案 0 :(得分:231)

使用find

find . -maxdepth 1 -name "*string*" -print

它将在当前目录中找到所有文件(删除maxdepth 1,如果你想要它递归),包含“string”并将其打印在屏幕上。

如果您想避免包含':'的文件,可以输入:

find . -maxdepth 1 -name "*string*" ! -name "*:*" -print

如果您想使用grep(但我认为没有必要,只要您不想检查文件内容),您可以使用:

ls | grep touch

但是,我再说一遍,find是一个更好,更清洁的解决方案。

答案 1 :(得分:13)

使用grep如下:

grep -R "touch" .

-R表示递归。如果您不想进入子目录,请跳过它。

-i表示“忽略大小写”。您可能会发现这也值得一试。

答案 2 :(得分:3)

-maxdepth选项应该在-name选项之前,如下所示。

find . -maxdepth 1 -name "string" -print

答案 3 :(得分:2)

find $HOME -name "hello.c" -print

这将在整个$HOME(即/home/username/)系统中搜索任何名为“hello.c”的文件并显示其路径名:

/Users/user/Downloads/hello.c
/Users/user/hello.c

但是,它不会与HELLO.CHellO.C匹配。要匹配不区分大小写,请传递-iname选项,如下所示:

find $HOME -iname "hello.c" -print

示例输出:

/Users/user/Downloads/hello.c
/Users/user/Downloads/Y/Hello.C
/Users/user/Downloads/Z/HELLO.c
/Users/user/hello.c

-type f选项传递给仅搜索文件:

find /dir/to/search -type f -iname "fooBar.conf.sample" -print
find $HOME -type f -iname "fooBar.conf.sample" -print

-iname可以在GNU或BSD(包括OS X)版本查找命令上运行。如果您的find命令版本不支持-iname,请使用grep命令尝试以下语法:

find $HOME | grep -i "hello.c"
find $HOME -name "*" -print | grep -i "hello.c"

或尝试

find $HOME -name '[hH][eE][lL][lL][oO].[cC]' -print

示例输出:

/Users/user/Downloads/Z/HELLO.C
/Users/user/Downloads/Z/HEllO.c
/Users/user/Downloads/hello.c
/Users/user/hello.c

答案 4 :(得分:0)

如果字符串位于名称的开头,则可以执行此操作

$ compgen -f .bash
.bashrc
.bash_profile
.bash_prompt

答案 5 :(得分:0)

grep -R "somestring" | cut -d ":" -f 1

答案 6 :(得分:0)

已提供的许多解决方案的替代方法是使用全局**。当您将bash与选项globstarshopt -s globstar)一起使用时,或者您使用zsh时,只需使用**即可。

**/bar

对名为bar的文件(可能在当前目录中包括文件bar)进行递归目录搜索。请注意,这不能与同一路径段内的其他形式的globing结合使用;在这种情况下,*运算符将恢复为通常的效果。

请注意,zshbash之间有细微的差别。尽管bash会遍历到目录的软链接,但zsh不会遍历。为此,您必须使用***/中的全局zsh

答案 7 :(得分:0)

find / -exec grep -lR "{test-string}" {} \;