很抱歉,如果问题很愚蠢:)
我需要一个脚本来使用for循环搜索文件中的一系列字符串,如果找到则输出'yes',如果找不到则输出'no'
我有一个文本文件'reg.txt'。内容如下
sam=23
jack=27
jim=35
dave=30
使用的脚本。内容r低于
#!bin/bash
declare file="/oracle/TR4/test/reg.txt"
declare regex=( jack jim sal don )
declare file_content=$( cat "${file}" )
for i in "${regex[@]}"
do
if [[ " $file_content " =~ $regex ]]
then
echo " the name $i is found"
else
echo " the name $i is not found"
fi
done
exit
但是在运行脚本时,似乎没有正确搜索条件。 ($ bash regcheck.sh)的输出如下所示
the name jack is found
the name jim is found
the name sal is found
the name don is found
显示sal和don的名字!那是错的。 使用'正则表达式','for loop'和'if'在一起时有什么特别的考虑吗? 请帮忙
答案 0 :(得分:1)
您需要与$i
匹配,而不是与$regex
匹配。将您的代码更改为
if [[ " $file_content " =~ "$i" ]]
整个代码:
#!/bin/bash
declare file="/oracle/TR4/test/reg.txt"
declare regex=( jack jim sal don )
declare file_content=$( cat "${file}" )
for i in "${regex[@]}"
do
if [[ " $file_content " =~ $i ]]
then
echo " the name $i is found"
else
echo " the name $i is not found"
fi
done
exit