如何在bash中将字符串的一部分与正则表达式匹配?

Red*_*son 1 regex linux bash shell scripting

我使用正则表达式来匹配许多具有相似名称的文件名.请参阅以下文件.

file1="CGInoimport"
file2="doCGIimport"
file3="donoCGInoimport"
file4="importCGIno"
Run Code Online (Sandbox Code Playgroud)

我正在使用for循环来遍历每个文件变量以检查正则表达式是否匹配.我试图隔离包含该单词的文件名CGI.这是我到目前为止所拥有的.

for (( i=1; i < 5; i++ )) ; do
    if [[ file$i =~ ^CGI$ ]] ; then
        echo "There is a CGI in the name"
    else
        echo "This shouldn't happen"
    fi
done
Run Code Online (Sandbox Code Playgroud)

问题出在每个人身上file,我得到了This shouldn't happen.我知道正则表达式有问题,但我不知道如何解决它.有什么建议?

如果需要进一步说明,请与我们联系.

Cha*_*ffy 5

正则表达式^CGI$只匹配整个字符串CGI.如果要匹配任何子字符串,请简单使用CGI.

这是因为在正则表达式中,^仅匹配字符串的开头("锚点"到开头),并且$仅在结尾处匹配.也就是说,在这里使用shell样式模式(使用=运算符而不是=~)更常规,并且只需使用通配符来禁用它们的隐式锚点.

最后,由于您想查找变量查找,因此需要使用变量间接.所以:

varname=file$i
if [[ ${!varname} = *CGI* ]]; then
  echo "There is a CGI in the name"
fi
Run Code Online (Sandbox Code Playgroud)

也就是说,更好的方法是使用数组.所以:

files=( CGInoimport doCGIimport donoCGInoimport importCGIno )
for file in "${files[@]}"; do
  [[ $file = *CGI* ]] && echo "There is CGI in the name $file"
done
Run Code Online (Sandbox Code Playgroud)

...或者,如果键可以是非数字或不连续的,则为关联数组:

declare -A files=(
  [file1]=CGInoimport
  [file2]=doCGIimport
  [file3]=donocCGInoimport
  [file4]=importCGIno
)
for key in "${!files[@]}"; do
  [[ ${files[file$key]} = *CGI* ]] && echo "There is CGI in $key"
done
Run Code Online (Sandbox Code Playgroud)