Shell Scripting finding text in a text file

16,516
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.

Share:
16,516
Matt
Author by

Matt

Besides being a developer i enjoy Music, Guitar, Drawing, Hiking, Movies, and Camping

Updated on June 05, 2022

Comments

  • Matt
    Matt almost 2 years

    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?