bash 使用 ls 和 grep 列出具有某些扩展名的文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1447625/
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
List files with certain extensions with ls and grep
提问by Mint
I just want to get the files from the current dir and only output .mp4 .mp3 .exe files nothing else. So I thought I could just do this:
我只想从当前目录中获取文件,只输出 .mp4 .mp3 .exe 文件。所以我想我可以这样做:
ls | grep \.mp4$ | grep \.mp3$ | grep \.exe$
But no, as the first grep will output just mp4's therefor the other 2 grep's won't be used.
但是不会,因为第一个 grep 将只输出 mp4,因此不会使用其他 2 个 grep。
Any ideas? PS, Running this script on Slow Leopard.
有任何想法吗?PS,在Slow Leopard 上运行这个脚本。
回答by meder omuraliev
Why not:
为什么不:
ls *.{mp3,exe,mp4}
I'm not sure where I learned it - but I've been using this.
我不确定我从哪里学到的 - 但我一直在使用它。
回答by Paused until further notice.
Use regular expressions with find
:
使用正则表达式find
:
find . -iregex '.*\.\(mp3\|mp4\|exe\)' -printf '%f\n'
If you're piping the filenames:
如果您正在管道文件名:
find . -iregex '.*\.\(mp3\|mp4\|exe\)' -printf '%ffind -E . -regex '.*\.(mp3|mp4|exe)'
' | xargs -0 dosomething
This protects filenames that contain spaces or newlines.
这可以保护包含空格或换行符的文件名。
OS X find
only supports alternation when the -E
(enhanced) option is used.
OS Xfind
仅在使用-E
(enhanced) 选项时支持交替。
ls | egrep '\.mp4$|\.mp3$|\.exe$'
回答by mob
egrep
-- extended grep -- will help here
egrep
-- 扩展 grep -- 会在这里有所帮助
ls *.mp4 *.mp3 *.exe
should do the job.
应该做的工作。
回答by Joshua K
the easiest way is to just use ls
最简单的方法是使用 ls
find -iname '*.mp3' -o -iname '*.exe' -o -iname '*.mp4'
回答by P Shved
Just in case: why don't you use find
?
以防万一:你为什么不使用find
?
ls *.mp4 *.mp3 *.exe
回答by camh
No need for grep. Shell wildcards will do the trick.
不需要grep。Shell 通配符可以解决问题。
shopt -s nullglob
If you have run
如果你跑了
shopt -s nocaseglob
then unmatched globs will be removed altogether and not be left on the command line unexpanded.
那么不匹配的 glob 将被完全删除,而不是留在命令行上未展开。
If you want case-insensitive globbing (so *.mp3 will match foo.MP3):
如果您想要不区分大小写的通配符(因此 *.mp3 将匹配 foo.MP3):
ls | grep -i -e '\.tcl$' -e '\.exe$' -e '\.mp4$'
回答by Hai Vu
In case you are still looking for an alternate solution:
如果您仍在寻找替代解决方案:
ls | grep "\.mp4$
\.mp3$
\.exe$"
Feel free to add more -e flags if needed.
如果需要,请随意添加更多 -e 标志。
回答by james2doyle
For OSX users:
对于 OSX 用户:
If you use ls *.{mp3,exe,mp4}
, it will throw an errorif one of those extensions has no results.
如果您使用ls *.{mp3,exe,mp4}
,如果这些扩展之一没有结果,它将抛出错误。
Using ls *.(mp3|exe|mp4)
will return all files matching those extensions, even if one of the extensions had 0 results.
Usingls *.(mp3|exe|mp4)
将返回与这些扩展名匹配的所有文件,即使其中一个扩展名有 0 results。
回答by vardamanpk
ls -R | findstr ".mp3"
ls -R | findstr ".mp3"
ls -R
=> lists subdirectories recursively
ls -R
=> 递归列出子目录