Jazzkatt Jazzkatt - 1 month ago 4x
Bash Question

Checking whether a filename matches a pattern in bash

I am trying to figure out how to setup a script that will do the following:

files in dir:


script(s) in dir:

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

I need to have a function that will select the file and run it through a specified script.

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

or some sorts. the script will be in the same location as the files/scripts it will utilize. in words, the script will run a specified script based on the start of the file name and the filetype/suffix. any help would be appreciated.


Selecting everything and filtering is more trouble than going pattern-by-pattern.

#      ^^^^- 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 ...

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

That said, if you really want to iterate over all files in the directory, use a case statement:

# 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" ;;