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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 19:25:10  来源:igfitidea点击:

List only numeric file names in directory

linuxbash

提问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 lsor grepcombo command to accomplish this objective?

有没有人知道一个lsgrep组合命令来完成这个目标?

I do have this much:

我有这么多:

ls -al | grep "[0-9].php"

采纳答案by ppolyzos

You can use regular expression when listing files:

您可以在列出文件时使用正则表达式:

ls [0-9]*

This was an easy and minimalistic approach at the above problem but I think a better solution is

这是解决上述问题的一种简单而简约的方法,但我认为更好的解决方案是

ls -al | grep -E '^[0-9]+\.php$'

as UncleZeiv explains below.

正如 UncleZeiv在下面解释的那样

回答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$'

-Eactivates 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 -regexargument 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 mvcommand is replaced by findwith the found filename.

命令中的{}诡计mv被替换find为找到的文件名。

回答by Philipp

Either use find(possibly combined with the -XXXdepthoptions):

要么使用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 lsor grep.

不要使用lsgrep