Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Conditionally add or append to a file in linux script

I need to modify a file via a script.
I need to do the following:
IF a specific string does NOT exist then append it.

So I created the following script:

#!/bin/bash  
if grep -q "SomeParameter A" "./theFile"; then  
echo exist  
else  
   echo doesNOTexist  
   echo "# Adding parameter" >> ./theFile    
   echo "SomeParameter A" >> ./theFile    
fi

This works but I need to make some improvements.
I think it would be better if I checked if "SomeParameter" exists and then see if it is followed by "A" or "B". If it is "B" then make it "A".
Otherwise append the string (like I do) BUT BEFORE the start of the last block of comments.
How could I do this?
I am not good in scripting.
Thanks!

like image 507
Jim Avatar asked Oct 22 '12 08:10

Jim


People also ask

How do you append a file in Unix shell script?

You do this by using the append redirection symbol, ``>>''. To append one file to the end of another, type cat, the file you want to append, then >>, then the file you want to append to, and press <Enter>.

What is $@ in bash script?

bash [filename] runs the commands saved in a file. $@ refers to all of a shell script's command-line arguments. $1 , $2 , etc., refer to the first command-line argument, the second command-line argument, etc. Place variables in quotes if the values might have spaces in them.

How do I append to a bash script?

To make a new file in Bash, you normally use > for redirection, but to append to an existing file, you would use >> . Take a look at the examples below to see how it works. To append some text to the end of a file, you can use echo and redirect the output to be appended to a file.

How do you add a file to a script in Linux?

In Linux, to append text to a file, use the >> redirection operator or the tee command.


1 Answers

First, change any SomeParameter lines if they already exist. This should work with lines like SomeParameter or SomeParameter B, with any number of extra spaces:

sed -i -e 's/^ *SomeParameter\( \+B\)\? *$/SomeParameter A/' "./theFile"

Then add the line if it doesn't exist:

if ! grep -qe "^SomeParameter A$" "./theFile"; then
    echo "# Adding parameter" >> ./theFile    
    echo "SomeParameter A" >> ./theFile    
fi
like image 196
l0b0 Avatar answered Sep 30 '22 09:09

l0b0