Shell脚本读取文件夹中具有特定开头和扩展名的每一个文件

njthzxwz  于 2023-03-13  发布在  Shell
关注(0)|答案(2)|浏览(203)

我对shell脚本很陌生。我有一个文件夹,里面的文件有顺序名称,例如。

ABC19001_1_good_(another random 4 characters or numbers).txt
ABC19001_1_good_notsoideal_(another random 4 characters or numbers).txt
ABC19001_2_good_(another random 4 characters or numbers).txt
ABC19001_2_good_notsoideal_(another random 4 characters or numbers).txt
ABC19002_1_good_(another random 4 characters or numbers).txt
...

有没有一种方法可以指定只阅读ABCxxxxx_x_good_(another random 4 characters or numbers).txt,而不读取shell脚本中包含notsoideal字符串的内容(类似于在python中使用正则表达式)?
谢谢你的帮助。
我尝试了$ABC19*.txt,它包括所有文件。我尝试了$ABC19*good_*{4}.txt来过滤掉notsoideal文件,但这不起作用。

4ioopgfo

4ioopgfo1#

针对2种特定场景中的每一种进行编程:

  • 包括“* 好 *",以及
  • 排除“不太理想”

所以...

ls AB19* | grep '_good_' | grep -v 'notsoideal'
tzxcd3kk

tzxcd3kk2#

Bash(和其他Bourne派生的shell)支持的文件名模式不是正则表达式。它们被称为“glob”模式。有关它们的详细信息,请参见glob - Greg's Wiki。glob模式的权威参考是Bash Reference Manual的模式匹配部分。
一个可能的glob模式可以完成您想要的任务:

ABC19*good_????.txt

$ABC19*good_*{4}.txt有两个问题。首先,$将导致试图扩展名为ABC19的变量。这可能会扩展为空,因此模式将等效于*good_*{4}.txt。其次,{}在团状结构中没有特殊意义。该模式匹配包含good_并以文字字符串{4}.txt结尾的文件名。正则表达式方言支持{...}模式。在这些方言中,.{4}(或某些.\{4\})匹配任意4个字符。

相关问题