Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/shell/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
检查文件名是否与bash中的模式匹配_Bash_Shell_Unix_Sh - Fatal编程技术网

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

检查文件名是否与bash中的模式匹配,bash,shell,unix,sh,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} [par

我正试图找出如何设置一个脚本,该脚本将执行以下操作:

目录中的文件:

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

看一看
case
语句,它有助于根据变量匹配模式选择不同的操作。顺便说一句,是您的朋友。您的意思是
a_*.txt
获取
1.sh
b_*.txt
获取
2.sh
,等等?关于所需行为的问题,请更具体一点——一个例子不足以建立一个模式。可以理解,如果一个给定名称有多个文件,则无法记住如何设置该名称,并且无法让它为每个文件运行脚本a_u.txt针对1.sh运行--b_u.txt针对1.sh运行--c_u*.txt再次针对2.sh运行