试图让grep变量

时间:2014-05-07 15:06:44

标签: variables grep

#!/bin/bash

echo "Please type the file name"
read filename
echo "Please type the word or phrase you wish to look for"
read string
grep '$string' /home/pi/$filename

我想知道如何让grep变量,所以我可以使用这样的代码:

if [ $var=~$string ];
then
echo "the string is there
else 
echo "sorry string doesn't exist"

1 个答案:

答案 0 :(得分:1)

将grep的输出分配给变量:

var = $(grep '$string' /home/pi/$filename)

修改

正如@staticx指出的那样,在你的情况下,你在$string grep并查看结果是否再次与$string匹配,只是看看grep是否通过管道找到元素会更容易wc -l

count = $(grep '$string' /home/pi/$filename | wc -l)
if [ count -gt 0 ]; then
    # do stuff
fi