2016-09-15 49 views
2

我试图找出如何建立一个脚本,将做到以下几点:在DIR检查文件名是否在bash的模式匹配

a_3.txt 
b_3.txt 
c_3.txt 

脚本(S):

文件目录:

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 

或某种形式。该脚本将与它将使用的文件/脚本位于相同的位置。换言之,脚本将根据文件名和文件类型/后缀的开始运行指定的脚本。任何帮助,将不胜感激。

+1

看看了'case'声明,这是适合基于变量匹配模式选择不同的动作。 – Barmar

+0

顺便说一句,http://shellcheck.net/是你的朋友。 –

+0

你的意思是'a _ *。txt'获得'1.sh','b _ *。txt'获得'2.sh'等?请在关于期望行为的问题上更具体 - 一个例子不足以建立模式。 –

回答

3

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

#!/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