pullhyphoonprotocol
pullhyphoonprotocol

Reputation: 217

Bash creating a string, if string already exists replace it

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

Upvotes: 1

Views: 815

Answers (3)

potong
potong

Reputation: 58351

This might work for you (GNU sed):

sed 'H;$!d;x;/few/!s/^/asd/;t;s//asd/;s/.//' file

Make a copy of the file in the hold space (first line will have a prepended newline).

At the end of the file, if few is not matched, insert the literal asd.

Otherwise, replace the first occurrence of few with asd and remove the introduced newline at the start of the file.

To replace all occurrences of few with asd use:

sed 'H;$!d;x;/few/!s/^/asd/;t;s//asd/g;s/.//' file

Alternative:

grep -q few file && sed 's/few/asd/' file || (echo asd; cat file)

Upvotes: 0

anubhava
anubhava

Reputation: 784868

Using a single awk you can use this:

awk 'FNR == NR {if (/few/) {n = 1; nextfile}; next}
FNR == 1 && !n {print "asd"} n {gsub(/few/, "asd")} 1' file file

Upvotes: 0

KamilCuk
KamilCuk

Reputation: 140880

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.

Upvotes: 3

Related Questions