如何循环遍历unix shell脚本中与正则表达式匹配的文件

pau*_*ith 6 regex unix bash shell

我希望能够循环遍历与特定模式匹配的文件列表.我可以让unix使用带有正则表达式的ls和egrep列出这些文件,但我找不到将其转换为迭代过程的方法.我怀疑使用ls不是答案.我们将非常感激地提供任何帮助.

我当前的ls命令如下所示:

ls | egrep -i 'MYFILE[0-9][0-9]([0][1-9]|1[0-2])([0][1-9]|[12][0-9]|[3][01]).dat'
Run Code Online (Sandbox Code Playgroud)

我希望上面的内容匹配:

  • MYFILE160418.dat
  • myFILE170312.DAT
  • MyFiLe160416.DaT

但不是:

  • MYOTHERFILE150202.DAT
  • MYFILE.DAT
  • myfile.csv

谢谢,

保罗.

123*_*123 6

您可以使用(GNU)find正则表达式搜索选项而不是解析ls.

find . -regextype "egrep" \
       -iregex '.*/MYFILE[0-9][0-9]([0][1-9]|1[0-2])([0][1-9]|[12][0-9]|[3][01]).dat' \
       -exec [[whatever you want to do]] {} \;
Run Code Online (Sandbox Code Playgroud)

哪里[[whatever you want to do]]是你想要的文件的名称,执行命令.

从手册页

-regextype type
          Changes  the regular expression syntax understood by -regex and -iregex tests 
          which occur later on the command line.  Currently-implemented types are 
          emacs (this is the default),posix-awk, posix-basic, posix-egrep and 
          posix-extended.

  -regex pattern
          File name matches regular expression pattern.  This is a match on the whole 
          path, not a search.  For example, to match a file named `./fubar3', you can 
          use the regular expression
          `.*bar.' or `.*b.*3', but not `f.*r3'.  The regular expressions understood by 
          find are by default Emacs Regular Expressions, but this can be changed with 
          the -regextype option.

  -iregex pattern
          Like -regex, but the match is case insensitive.
Run Code Online (Sandbox Code Playgroud)


pau*_*ith 5

基于 Andy K 提供的链接,我使用以下内容根据我的匹配标准进行循环:

for i in $(ls | egrep -i 'MYFILE[0-9][0-9]([0][1-9]|1[0-2])([0][1-9]|[12][0-9]|[3][01]).dat' ); do             
 echo item: $i;         
done
Run Code Online (Sandbox Code Playgroud)

  • 不要将 `ls` 输出用于任何用途。`ls` 是一个用于交互式查看目录元数据的工具。任何用代码解析“ls”输出的尝试都会被破坏。Glob 更加简单和正确:“for file in *.txt”。阅读[解析 ls](http://mywiki.wooledge.org/ParsingLs) (2认同)