2

如果我有一个字符串:

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

和一个数组

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

如何有效地检查字符串中的匹配项?

4

2 回答 2

3

您可以遍历数组并使用bash 子字符串检查

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

或者,如果您想避免循环并且只关心文件名是否匹配,则可以使用@bash扩展 globbing的形式。以下示例假定数组文件名不包含|.

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
于 2013-09-27T02:18:25.730 回答
0

要与文件名完全匹配:

#!/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
于 2013-09-27T03:00:20.860 回答