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!
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>.
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.
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.
In Linux, to append text to a file, use the >> redirection operator or the tee command.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With