我正在使用正则表达式来匹配具有相似名称的许多文件名。请参阅下面的文件。
file1="CGInoimport"
file2="doCGIimport"
file3="donoCGInoimport"
file4="importCGIno"
我正在使用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
问题是每一个file
,我正在得到This shouldn't happen
。我知道正则表达式有问题,但我不知道如何解决。有什么建议?
让我知道是否需要进一步的解释。
^CGI$
仅当整个字符串为时,正则表达式才匹配CGI
。如果要匹配任何子字符串,请简单地使用CGI
。
这是因为在正则表达式中,^
仅在字符串的开头(“ anchors”到开头)匹配,并且$
仅在结尾匹配。也就是说,在这里使用shell样式的模式(使用=
运算符而不是=~
)是更常规的做法,并且仅使用通配符来禁用其隐式锚定。
最后,由于要通过变量查找进行查找,因此需要使用变量间接寻址。所以:
varname=file$i
if [[ ${!varname} = *CGI* ]]; then
echo "There is a CGI in the name"
fi
也就是说,更好的方法是使用数组。所以:
files=( CGInoimport doCGIimport donoCGInoimport importCGIno )
for file in "${files[@]}"; do
[[ $file = *CGI* ]] && echo "There is CGI in the name $file"
done
...或者,如果键可以是非数字或不连续键,则为一个关联数组:
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
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句