Matt
Matt

Reputation: 2843

Shell Scripting finding text in a text file

i am trying to check for a string in a text file. If string1 does not exisit then add string1 after string 2. Else string1 exists do nothing.

Here is what i have so far:

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

Also how can include the "/" character in my strings?

Upvotes: 3

Views: 17110

Answers (2)

krtek
krtek

Reputation: 26617

You can use grep, for example like this :

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

Upvotes: 0

Dennis Williamson
Dennis Williamson

Reputation: 360693

if grep -qs string1 myfile
then
    sed '/string1/ a\ string2' myfile
fi

However, you could skip the if since sed is testing for the existence of the string anyway. That way, you're only reading the file once instead of twice. Use sed -i if you want the change to be made to the file in-place.

Upvotes: 4

Related Questions