Sunday, March 13, 2022

[SOLVED] Bash creating a string, if string already exists replace it

Issue

I would like to achieve this procedure. I have this command: sed -i -e 's/few/asd/g' /usr/local/sbin/.myappenv This command works if in the file .myappenv there is a few string text. But this command fails to simply create the asd text wheter or not the few is found.

So, if there is the few text, it should replace it, if few text is missing, just create it on the first line.

EDIT_:

It should create the string on the first line of the document .myappenv, it should only be created if there is no coincidence.

The file .myappenv should contain =>

asd

If the file is already populated with few just replace it =>

asd

Solution

if there is the few text, it should replace it, if few text is missing, just create it on the first line.

That's an if.

if <file has text>; then <replace text>; else <add text to first line>; fi

or in bash:

file=/usr/local/sbin/.myappenv
if grep -q few "$file"; then
     sed 's/few/asd/' "$file"
else
     { 
        echo asd
        cat "$file"
     } > "$file".tmp
     mv "$file".tmp "$file"
fi

How to test if string exists in file with Bash? https://unix.stackexchange.com/questions/99350/how-to-insert-text-before-the-first-line-of-a-file and https://mywiki.wooledge.org/BashGuide/TestsAndConditionals . You might interest yourself in some automation methods, like ansible lineinfile or chezmoi depending on the goal.



Answered By - KamilCuk
Answer Checked By - Dawn Plyler (WPSolving Volunteer)