我试图弄清楚如何设置一个脚本来执行以下操作:
目录中的文件:
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/