Replace or add a string to a file

I know sed can replace a piece of string within a text file like this :

sed -i 's/oldstring/newstring/g' test.txt

But, how do I replace the line if it exists and automatically add it on a new line if it doesn't exist?

Thanks.

Edit : Thank you for your responses. As per the requests on your comments and answer, here's more details :

  • I want to check the existence of the old string and replace it with the new string if it exists.
  • I want to add the new string in a new line at the end of the txt file if the old string does not exist
  • If there are multiple occurances of the same string, it would be an error since its a config file.The other occurances can be removed after replacing the first occurance.

One way to do this it to bring grep into the equation. First check whether the file contains the string with a quick grep and then append or substitute accordingly:

grep -q string file && 
    sed -i 's/string/newstring/' file || echo "newstring" >> file

The above is a shorthand way of writing:

if grep -q string file; then 
    sed -i 's/string/newstring/' file
else
    echo "newstring" >> file
fi

Personally, however, I would use perl for this instead. Just read the file once and set a variable to 1 if the substitution was made. Then, at the end, add the string if the variable is not 1:

perl -lpe '$i=1 if s/oldstring/newstring/; 
           END{print "newstring" if $i!=1;}' file > tmpfile && mv tmpfile file

This should achieve what is required:

grep -q "oldstring" test.txt
if [ $? -eq 1 ]; then
    echo "newstring" >> test.txt
else
    sed -i 's/oldstring/newstring/g' test.txt
fi

Using AWK:

<<<"$(<in)" awk '{if(/foo/){x=sub(/foo/, "bar", $0)};print}END{if(x!=1){print "bar"}}' >in
% cat in1
string oldstring string
% cat in2
string foo string
% <<<"$(<in1)" awk '{if(/oldstring/){x=sub(/oldstring/, "newstring", $0)};print}END{if(x!=1){print "newstring"}}' >in1
user@user-X550CL ~/tmp % cat in1
string newstring string
% <<<"$(<in2)" awk '{if(/oldstring/){x=sub(/oldstring/, "newstring", $0)};print}END{if(x!=1){print "newstring"}}' >in2
% cat in2
string foo string
newstring