2

Sample script is shown below:

#!/bin/bash
sed -i~ 's/user1/user2/g' myfile.txt

It replaces user1 with user2 in myfile.txt

How can I change above script to get confirmation that the script found user1 & replaced it with user2?

Basically, if it doesn't find user1, it should give an alert message on the command prompt.

Thanks!

1
  • You could have sed touch a flag file if it does a successful substitution. As an optimization, only do it for the first match. If your input files are too large for the grep && sed and diff solutions, it might be worth piecing together a somewhat more complex sed script. Commented Oct 19, 2011 at 6:02

2 Answers 2

2

An alternative to diffing after is to grep before:

grep -q 'user1' myfile.txt && sed -i~ 's/user1/user2/g' myfile.txt || echo "user1 not there"

The -q means that grep runs quietly and returns success if found, so then and only then will it go on to do the replacement.

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

Comments

1

Try diff tool:

fgrep -q 'user1'  myfile.txt 2>&1 1>/dev/null
if [ "$?" -eq 0 ]; then
   echo " user1 found."
fi
...
diff -q myfile.txt myfile.txt~ 2>&1 1>/dev/null
if [ "$?" -eq 1 ]; then
   echo " Match found & Replaced."
fi

2 Comments

I've 5 sed commands in my script & I really want to check each of those string being replaced or not. How can I do that?
@Mike, you can split the sed operations into distinct commands and do what John says after each one.

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.