bash 列出名称中只有数字的文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/30527166/
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 that only have number in names
提问by PerseP
I have a directory with these files:
我有一个包含这些文件的目录:
1.html 22.html 333.html zxc.html
I want to get a list of the html files that only have digits in their name:
我想获取名称中仅包含数字的 html 文件列表:
1.html 22.html 333.html
I thought this would work
我以为这会奏效
find . -regex '^[0-9]+\.html'
or
或者
ls -al | grep -E '^[0-9]+\.html$'
But I get nothing. My idea is to get the html files with only digits in their names and pass them to sed to do a substitution.I'm using linux and bash
但我什么也得不到。我的想法是获取名称中只有数字的 html 文件,并将它们传递给 sed 进行替换。我正在使用 linux 和 bash
回答by Biffen
find
's -regex
matches against the whole path, not just the filename (I myself seem to forget this once for every time I use it).
find
的-regex
匹配整个路径,而不仅仅是文件名(我自己似乎每次使用它时都会忘记一次)。
Thus, you can use:
因此,您可以使用:
find . -regex '.*/[0-9]+\.html'
(^
and $
aren't necessary since it always tests against the whole path.)
(^
并且$
不是必需的,因为它总是针对整个路径进行测试。)
Using find
also has advantages when you want to do something with the files, e.g. using the built-in -exec
, -print0
and pipe to xargs -0
or even (using Bash):
find
当您想对文件做一些事情时,使用也有优势,例如使用内置的-exec
,-print0
和管道xargs -0
甚至(使用 Bash):
while IFS='' read -r -d '' file
do
# ...
done < <(find . -regex '.*/[0-9]+\.html' -print0)
echo
with a glob, ls|grep
, etc. tend to stop working when filenames contain spaces (or even newlines) (which I realise won't happen in this case; it's more of a matter of future-proofing and making good habits).
echo
ls|grep
当文件名包含空格(甚至换行符)时,使用 glob、等往往会停止工作(我意识到在这种情况下不会发生这种情况;这更像是一个面向未来和养成良好习惯的问题)。
回答by Tom Fenech
Use an extended glob:
使用扩展的 glob:
$ shopt -s extglob
$ echo +([0-9]).html
1.html 22.html 333.html
With extglob
enabled, +(pattern)
matches one or more of pattern
. Note that I am just using echo
to show which files match - how you use the glob depends on what you want to do with it.
与extglob
启用,+(pattern)
相匹配的一种或多种pattern
。请注意,我只是echo
用来显示哪些文件匹配 - 您如何使用 glob 取决于您想用它做什么。
To print each file on a separate line, you can use:
要在单独的行上打印每个文件,您可以使用:
printf '%s\n' +([0-9]).html
Each file matching the pattern is passed as a separate argument to printf
so you don't have to worry about things like spaces or other interesting characters in filenames.
每个与模式匹配的文件都作为单独的参数传递给,printf
因此您不必担心文件名中的空格或其他有趣字符之类的问题。
To iterate over these files, it's as simple as:
要遍历这些文件,就像这样简单:
for file in +([0-9]).html; do
echo "$file"
done
Again, the shell takes care of any potential problems with interesting filenames, so you don't have to worry about it.
同样,shell 会处理有趣的文件名的任何潜在问题,因此您不必担心。