2

If I have a string:

s='path/to/my/foo.txt'

and an array

declare -a include_files=('foo.txt' 'bar.txt');

how can I check the string for matches in my array efficiently?

2 Answers 2

3

You could loop through the array and use a bash substring check

for file in "${include_files[@]}"
do 
   if [[ $s = *${file} ]]; then
     printf "%s\n" "$file"
   fi
done

Alternately, if you want to avoid the loop and you only care that a file name matches or not, you could use the @ form of bash extended globbing. The following example assumes that array file names do not contain |.

shopt -s extglob
declare -a include_files=('foo.txt' 'bar.txt');
s='path/to/my/foo.txt'
printf  -v pat "%s|" "${include_files[@]}"
pat="${pat%|}"
printf "%s\n" "${pat}"
#prints foo.txt|bar.txt
if [[ ${s##*/} = @(${pat}) ]]; then echo yes; fi
Sign up to request clarification or add additional context in comments.

Comments

0

For an exact match to the file name:

#!/bin/bash

s="path/to/my/foo.txt";
ARR=('foo.txt' 'bar.txt');
for str in "${ARR[@]}"; 
do 
  # if [ $(echo "$s" | awk -F"/" '{print $NF}') == "$str" ]; then
  if [ $(basename "$s") == "$str" ]; then  # A better option than awk for sure...
     echo "match"; 
  else 
     echo "no match"; 
  fi; 
done

2 Comments

It's not necessary to use awk to strip off the part before the last slash. Bash parameter expansion can do this "${s##*/}" or the basename utility.
Indeed. Didn't occur to me right away. Thanks. I have added one of these nice options...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.