2012-07-04 67 views
103

我一直在寻找一个命令,它将从当前目录返回文件名中包含一个字符串的文件。我看到locatefind命令可以找到以first_word*开头或以*.jpg结尾的文件。Linux - 查找包含字符串名称的文件

如何返回文件名中包含字符串的文件列表?例如,2012-06-04-touch-multiple-files-in-linux.markdown是当前目录中的文件。

我怎样才能返回这个文件和其他包含字符串touch?使用命令,如find '/touch/'

+0

的问题是,如果你find命令的版本不支持-iname,使用grep命令试试下面的语法混乱。你想查找包含一个字符串的文件,或者其名称*包含所述字符串的文件吗?第一个问题用'man grep'回答,第二个用'man find'回答。你为什么会谷歌而不是使用男人,我不知道。 –

+1

谢谢!第一句没有指定是文件内容还是文件名。更新。 – Dru

回答

157

使用find

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

它会查找当前目录下的所有文件(删除maxdepth 1如果你想让它递归)包含“串”,将打印在屏幕上。

如果你想避免包含文件“:”,你可以输入:

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

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

ls | grep touch

但是,我再说一遍,find是你的任务一个更好,更洁净的解决方案。

+0

谢谢@Zagorax。这完全是。希望命令不是那么久,但是ayee :) – Dru

+1

@Dru,修改覆盖案件,如果你想避免冒号。 'find'是一个非常强大的工具,它必须以某种方式'长'。 :) – Zagorax

+0

感谢第一个完美无缺地返回任何内容。 – Dru

12

使用grep如下:

grep -R "touch" . 

-R装置递归。如果你不想进入子目录,那么跳过它。

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

+0

太好了。我注意到一些文件内容遵循':'。反正有什么可以隐瞒吗?也许使用一个选项? – Dru

+1

尝试:'grep -R“touch”。 | cut -d“:”-f 2“ – carlspring

+0

这似乎只产生文件的内容。你基本上回答了我的问题,但我可以尝试挖掘一些内容。 – Dru

0

如果字符串是在名称的开头,你可以做到这一点

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

'compgen'对于这颗指甲不是一个合适的锤子。这个很少使用的工具被设计为列出*可用命令*,因此它列出了* current *目录中的文件(可能是脚本),它既不会递归也不会查看文件名或文件名的开头内容,使其大多无用。 – msanford

2

-maxdepth选项应该是-name选项之前,像下面,

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

你必须在“字符串”之前和之后加*。 – Aaron

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

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

/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 $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 
0
grep -R "somestring" | cut -d ":" -f 1 
+0

这似乎是一个不同问题的答案 - 但是因为你没有提供任何解释,这对提问者或任何其他人都不明显。 –

相关问题