如何在shell中列出递归目录中特定类型的文件?
我们如何找到嵌套目录中存在的特定类型的文件,即 doc pdf 文件。
我尝试过的命令:
$ ls -R | grep .doc
但是如果有像 alok.doc.txt
这样的文件名,该命令也会显示该文件名,这显然不是我想要的。我应该使用什么命令?
How can we find specific type of files i.e. doc pdf files present in nested directories.
command I tried:
$ ls -R | grep .doc
but if there is a file name like alok.doc.txt
the command will display that too which is obviously not what I want. What command should I use instead?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
如果您更喜欢使用“ls”和“grep”,则可以在 grep 命令中使用正则表达式执行您想要的操作(结尾的“$”字符表示 .doc 必须位于行的末尾。这将排除“file.doc.txt”):
有关使用 grep 与正则表达式的更多信息,请参阅 man。
If you are more confortable with "ls" and "grep", you can do what you want using a regular expression in the grep command (the ending '$' character indicates that .doc must be at the end of the line. That will exclude "file.doc.txt"):
More information about using grep with regular expressions in the man.
ls
命令输出主要供人类阅读。对于自动化处理的高级查询,您应该使用更强大的find
命令:就像您有 bash 4.0++
ls
command output is mainly intended for reading by humans. For advanced querying for automated processing, you should use more powerfulfind
command:As if you have bash 4.0++
这也将显示路径。
This will show the path as well.
可以使用的其他一些方法:
echo *.{pdf,docx,jpeg}
stat -c %n * | grep 'pdf\|docx\|jpeg'
Some of the other methods that can be used:
echo *.{pdf,docx,jpeg}
stat -c %n * | grep 'pdf\|docx\|jpeg'
我们也有类似的问题。我们想要一个包含路径的列表,其中包含 etc 目录中的所有配置文件。这很有效:
它提供了所有 .conf 文件及其路径的良好列表。输出看起来像:
但是,我们想对所有这些文件执行一些操作,例如 grep 这些文件以在所有文件中查找单词或设置。因此,我们
通过 grep 查找 /etc 中包含“ServerName”等设置的所有配置文件 输出如下:
希望您发现它有用。
席德
We had a similar question. We wanted a list - with paths - of all the config files in the etc directory. This worked:
It gives a nice list of all the .conf file with their path. Output looks like:
But, we wanted to DO something with ALL those files, like grep those files to find a word, or setting, in all the files. So we use
to find via grep ALL the config files in /etc that contain a setting like "ServerName" Output looks like:
Hope you find it useful.
Sid
如果您的文件扩展名与文件类型不匹配,您可以使用
file
实用程序。find $PWD -type f -exec file -N \{\} \; | grep "PDF 文档" | awk -F: '{print $1}'
您可以使用要开始搜索的目录来代替
$PWD
。file
甚至打印出 he PDF版本。If you have files with extensions that don't match the file type, you could use the
file
utility.find $PWD -type f -exec file -N \{\} \; | grep "PDF document" | awk -F: '{print $1}'
Instead of
$PWD
you can use the directory you want to start the search in.file
prints even out he PDF version.