在bash脚本中使用ls命令时模式匹配。

时间:2021-03-16 13:56:21

In a sh script, I am trying to loop over all files that match the following pattern
abc.123 basically abc. followed by only numbers, number following . can be of any length.
Using

在sh脚本中,我尝试遍历与以下模式abc匹配的所有文件。123年美国广播公司(abc)。后面跟着数字,后面跟着数字。可以是任意长度。使用

$ shopt -s extglob
$ ls abc.+([0-9])

$ shopt -s extglob $ ls abc.+([0-9])

does the job but on terminal and not through the script. How can I get only files that match the pattern?

只在终端上执行任务,而不是通过脚本执行。如何只获得与模式匹配的文件?

2 个解决方案

#1


1  

If you're using sh and not bash, and presumably you also want to be POSIX compliant, you can use:

如果您使用的是sh而不是bash,并且假定您也希望与POSIX兼容,您可以使用:

for f in ./*
do
    echo "$f" | grep -Eq '^\./abc.[0-9]+$' && continue
    echo "Something with $f here"
done

It will work fine with filenames with spaces, quotes and such, but may match some filenames with line feeds in them that it shouldn't.

它可以很好地处理带有空格、引号等的文件名,但也可以将某些文件名与不应该匹配的行提要匹配。

If you tagged your question bash because you're using bash, then just use extglob like you described.

如果您标记了您的问题bash,因为您正在使用bash,那么就像您描述的那样使用extglob。

#2


2  

if I understood you right, the pattern could be translated into regex:

如果我没理解错的话,这个模式可以翻译成regex:

^abc\.[0-9]+$

so you could

所以你可以

keep using ls and grep the output. for example:

继续使用ls和grep输出。例如:

ls *.*|xargs -n1|grep -E '^abc\.[0-9]+$'

or use find

或者使用发现

find has an option -regex

find有一个选项-regex

#1


1  

If you're using sh and not bash, and presumably you also want to be POSIX compliant, you can use:

如果您使用的是sh而不是bash,并且假定您也希望与POSIX兼容,您可以使用:

for f in ./*
do
    echo "$f" | grep -Eq '^\./abc.[0-9]+$' && continue
    echo "Something with $f here"
done

It will work fine with filenames with spaces, quotes and such, but may match some filenames with line feeds in them that it shouldn't.

它可以很好地处理带有空格、引号等的文件名,但也可以将某些文件名与不应该匹配的行提要匹配。

If you tagged your question bash because you're using bash, then just use extglob like you described.

如果您标记了您的问题bash,因为您正在使用bash,那么就像您描述的那样使用extglob。

#2


2  

if I understood you right, the pattern could be translated into regex:

如果我没理解错的话,这个模式可以翻译成regex:

^abc\.[0-9]+$

so you could

所以你可以

keep using ls and grep the output. for example:

继续使用ls和grep输出。例如:

ls *.*|xargs -n1|grep -E '^abc\.[0-9]+$'

or use find

或者使用发现

find has an option -regex

find有一个选项-regex