3

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?

2 Answers 2

4
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.

Sign up to request clarification or add additional context in comments.

1 Comment

Sorry i made a typo, sed should be checking for the existence of string2.
0

You can use grep, for example like this :

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

2 Comments

The brackets and command substitution aren't necessary. The -eq 1 won't pass because the exit code is not output, it's held in $?.
Yeah, you're right, I'll modify the code. Concerning the bracket, I like to put them even if they aren't necessary, I find the code more readable with them.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.