bash 仅列出目录中的数字文件名
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3151338/
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 only numeric file names in directory
提问by gurun8
I have a list of files with numeric file names (e.g. #.php, ##.php or ###.php) that I'd like to copy/move in one fell swoop.
我有一个带有数字文件名(例如#.php、##.php 或###.php)的文件列表,我想一举复制/移动这些文件。
Does anyone know of an ls
or grep
combo command to accomplish this objective?
有没有人知道一个ls
或grep
组合命令来完成这个目标?
I do have this much:
我有这么多:
ls -al | grep "[0-9].php"
采纳答案by ppolyzos
回答by Paused until further notice.
In Bash, you can use extended pattern matching:
在 Bash 中,您可以使用扩展模式匹配:
shopt -s extglob
ls -l +([0-9]).php
which will find files such as:
它将找到诸如以下文件:
123.php
9.php
but not
但不是
a.php
2b.php
c3.php
回答by UncleZeiv
Amend it like this:
修改成这样:
ls -al | grep -E '^[0-9]+\.php$'
-E
activates the extended regular expressions.
-E
激活扩展的正则表达式。
+
requires that at least one occurrence of the preceding group must appear.
+
要求必须至少出现一次前一组。
\.
escape dot otherwise it means "any character."
\.
转义点,否则表示“任何字符”。
^
and $
to match the entire filename and not only a part.
^
并$
匹配整个文件名,而不仅仅是一部分。
Single quotes to prevent variable expansion (it would complain because of the $
).
单引号以防止变量扩展(由于 ,它会抱怨$
)。
回答by unwind
Use find:
使用查找:
$ find . -regex '^[0-9]+\.php' -exec mv '{}' dest/ ';'
Note that the -regex
argument does a search, not a match, which is why the ^ is there to anchor it to the start. This also assumes that the files are in the same directory (.) as the one you're in when running the command.
请注意,-regex
参数进行搜索,而不是匹配,这就是为什么 ^ 将其锚定到开头的原因。这还假设这些文件与您在运行命令时所在的目录位于同一目录 (.) 中。
The {}
trickery in the mv
command is replaced by find
with the found filename.
命令中的{}
诡计mv
被替换find
为找到的文件名。
回答by Philipp
Either use find
(possibly combined with the -XXXdepth
options):
要么使用find
(可能与-XXXdepth
选项结合使用):
find . -mindepth 1 -maxdepth 1 -regex '^[0-9]+\.php' -exec mv '{}' dest/ ';'
Or use the builtin regex capabilities:
或者使用内置的正则表达式功能:
pattern='^[0-9]+\.php$'
for file in *.php
do
[[ $file =~ $pattern ]] && echo "$file"
done
Don't use ls
or grep
.
不要使用ls
或grep
。