Q:

Find filenames using variables in a for loop in UNIX

I have some files of this form: 2014.144.09.27.56.0195.IU.SDV.00.BHZ.M.SAC and I want to extract the SDV, 00 ,BHZ variables, in order to find a file, of this form  ./POLEZEROFILES/SAC_PZs_IU_SDV_BHZ_00_2014.112.19.50.00.0000_2599.365.23.59.59.99999, using these variables. I am using this forloop, that for every ".SAC" file, it finds the corresponding "SAC_PZs_" file, with the same variables in the filename.
#!/bin/sh
ALIST=(*SAC)

for ((i=0;i<${#ALIST[@]};i++));do

A="${ALIST[i]}"

staname=`ls "$A" | awk -F"[_.]" '{print $8}'`
staXX=`ls "$A" | awk -F"[_.]" '{print $9}'`
stacomp=`ls "$A" | awk -F"[_.]" '{print $10}'`

B=`find ./POLEZEROFILES -name "SAC*_${staname}_*${stacomp}_*${staXX}*" -print`
echo "${A}" "${B}"
done

This code works for some filenames, but in some cases it outputs 2 filenames, ignoring the 00 variable.For example,
for this $A:
2014.144.09.27.33.0195.IU.RSSD.00.BHZ.M.SAC

it outputs 2 $B:

./POLEZEROFILES/SAC_PZs_IU_RSSD_BHZ_10_2011.209.05.56.00.0000_2599.365.23.59.59.99999
./POLEZEROFILES/SAC_PZs_IU_RSSD_BHZ_00_2011.208.18.13.59.0000_2599.365.23.59.59.99999

The second output is the right one.
Can anyone figure out the problem?

A:

Not related to your problem but a general comment. You don't need ls in those awk lines. echo will work just fine (as will awk ... <<<"$A").
Your problem is that your pattern matches too loosely.
Your second to last * consumes up to the 00.0000.... bit in your first filename and then matches. You need to anchor your desired patterns better. So if you know that stacomp and staXX will be next to each other drop the * between them. If you don't know that then at least put a _ after staXX to anchor the following character.
There's also no need for the array and manual for loop here.
Just for A in *SAC; do will work for your loop.

