bash - 检查文件名是否与 bash 中的模式匹配

标签 bash shell unix sh

我试图弄清楚如何设置一个脚本来执行以下操作:

目录中的文件:

a_3.txt  
b_3.txt  
c_3.txt

目录中的脚本:

1.sh  # run this for a_*.txt
2.sh  # run this for b_*.txt or c_*.txt

我需要一个函数来选择文件并通过指定的脚本运行它。

    fname = "c_*.txt" then
    if "${fname}" = "c_*.txt"
    ./1.sh ${fname} [param1] [param2]
fi

或者某种。该脚本将与其使用的文件/脚本位于同一位置。换句话说,该脚本将根据文件名的开头和文件类型/后缀运行指定的脚本。任何帮助将不胜感激。

最佳答案

选择所有内容并进行过滤比逐个模式更麻烦。

#!/bin/bash
#      ^^^^- bash is needed for nullglob support

shopt -s nullglob # avoid errors when no files match a pattern

for fname in a_*.txt; do
  ./1.sh "$fname" param1 param2 ...
done

for fname in b_*.txt c_*.txt; do
  ./2.sh "$fname" param2 param3 ...
done

也就是说,如果您确实想要迭代目录中的所有文件,请使用 case 语句:

# this is POSIX-compliant, and will work with #!/bin/sh, not only #!/bin/bash

for fname in *; do # also consider: for fname in [abc]_*.txt; do
  case $fname in
    a_*.txt)         ./1.sh "$fname" param1 param2 ... ;;
    b_*.txt|c_*.txt) ./2.sh "$fname" param1 param2 ... ;;
    *)               : "Skipping $fname" ;; # this will be logged if run with bash -x
  esac
done

关于bash - 检查文件名是否与 bash 中的模式匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39517764/

相关文章:

bash - 如何使用 Bash 重命名在前面添加连字符?

linux - 如何从命令内部解析中转义单引号?

bash - env -0 转储环境。但是如何加载呢?

shell - docker run bash脚本无法退出

java - 我对数据抽象定义的回答

linux - 比较文件中的值

bash ascii 到十六进制

java - Linux 版本检查 Linux 命令或 Java 代码

linux - 每 15 分钟运行一次 crontab 不适用于 linux redhat

c++ - Python 将输入重定向到子进程