Jazzkatt
Jazzkatt

Reputation: 65

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:

a_3.txt  
b_3.txt  
c_3.txt

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]
fi

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.

Upvotes: 2

Views: 3463

Answers (1)

Charles Duffy
Charles Duffy

Reputation: 295954

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

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

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" ;; # this will be logged if run with bash -x
  esac
done

Upvotes: 3

Related Questions