变量不能用于grep模式匹配

时间:2018-09-11 06:55:18

标签: shell grep

我正在尝试使用Shell脚本从一个文件中获取字符串,然后使用它来获取匹配的句子。

脚本如下:

function find_str (){
    echo $1
    grep -e "\/$1" info.txt
}

for word in $(<./name.TXT); do
   #egrep -w "$word" info.txt  #this can't work either
   find_str $word
done 

事实证明,find_str $word无法匹配诸如// WORD1 balabala之类的字符串

对这段简短的脚本有何建议?

1 个答案:

答案 0 :(得分:0)

“ / $ 1”部分是什么?您是否在寻找斜线?而您需要该功能吗?

$ cat > info.txt
testing 123 dog
nothing matches a catalyst
doggerel is not poetry
my cat is a maine coone

$ cat > name.txt
dog cat

使用-w和gnu grep时,仅列出具有匹配的整个单词的行:

$ for word in $(<name.txt); do grep -w "$word" info.txt; done
testing 123 dog
my cat is a maine coone

没有-w标志,则列出所有包含匹配项的行:

$ for word in $(<name.txt); do grep "$word" info.txt; done
testing 123 dog
doggerel is not poetry
nothing matches a catalyst
my cat is a maine coone