检查文本文件是否包含字符串

时间:2015-06-17 05:11:10

标签: bash shell

我有一个包含任务列表的文本文件,每次我想添加任务时都要检查它是否存在于文本文件中。我尝试使用grep,但它没有用,因为每个任务都有它的编号。

在$ 2参数中我传递一个String,这是我要添加到todo.txt的任务     我试过用这个:

if grep -Fxq “$2” todo.txt  
then
    #do something 
else 
    #do something

这是文本文件的示例:

    Tasks: 
        1- Go to the gym
        2- Go to work
        3- Submit your project

2 个答案:

答案 0 :(得分:0)

这样做:

if grep -iq "$2" file;then #Assumed you want it to be case insensitive (-i)
echo "do something"
else
echo "do something else"
fi

注意:

  1. 将你的arguemnt $2传递给引文,因为它似乎包含空格
  2. 传递任务的全名(需要是唯一的)

答案 1 :(得分:-1)

你可以使用 grep" $ 2" todo.txt 并检查退出代码 - $?它返回。如果找到则返回0,如果未找到则返回非零。

相关问题