Shell Scripting finds text in a text file

I am trying to check a string in a text file. If string1 does not exist, add string1 after line 2. Else string1 does nothing.

Here is what I still have:

if [ string1 does not exisit ]  //Stuck at this
then
sed '/string2/ a\ string1' myfile
fi

Also, how can the "/" character be included in my lines?

+3
source share
2 answers
if grep -qs string1 myfile
then
    sed '/string1/ a\ string2' myfile
fi

However, you can skip if, because it sedstill checks for the existence of the string. Thus, you read the file only once, not twice. Use sed -iif you want to make changes to the file in place.

+4
source

You can use grep, for example, as follows:

$(grep -q "string1" myfile)
if [ $? -eq 1 ]; then
    sed '/string1/ a\ string2' myfile
fi
0
source

Source: https://habr.com/ru/post/1795554/


All Articles