LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - Newbie (http://www.linuxquestions.org/questions/linux-newbie-8/)
-   -   bash script to create text in a file or replace value of text if already exists (http://www.linuxquestions.org/questions/linux-newbie-8/bash-script-to-create-text-in-a-file-or-replace-value-of-text-if-already-exists-668674/)

knightto 09-09-2008 09:12 AM

bash script to create text in a file or replace value of text if already exists
 
I have 20+ servers built with the same build of RedHat.
There are multiple files who's contents I need to change on each box.
I'm guessing some sort of script that does the following is what I need but don't know syntax.
--
Script that does:
1. Searches each file for specific text.
a. if text not found (ADD FIELD=VALUE)
b. if text IS found (REMOVE LINE and ADD FIELD=VALUE).

I'm looking to:
add/modify grub password in /etc/grub.conf
change PUBLIC to 'other value' in /etc/snmp/snmp.conf
add/modify lines in /etc/sysctl.conf

IF someone could give me an idea on some sort of IF loop that looks for TEXT, replaces entire line if exists
IF doesn't exist
ADD LINE

That should help.

Thanks in advance

chrism01 09-09-2008 08:46 PM

I'd recommend Perl for that. Im hoping you don't allow root ssh logins. Instead designate a normal user to have sufficient privs via sudo and use that.Perl has modules for you to be able to script your stuff even under those requirements.
See
http://perldoc.perl.org/
http://www.perlmonks.org/?node=Tutorials
search.cpan.org


Actually, this is exactly the sort of issue Perl was originally designed for. There's even an O'Reilly book:
http://oreilly.com/catalog/9781565926097/index.html (Perl for System Admin)

chankle 09-09-2008 11:50 PM

Hi, here's what I came up with:


Code:

SEARCH_TEXT="net.ipv4.ip_forward"
REPLACE_TEXT="net.ipv4.ip_forward = some_other_value"
FILE='sysctl.conf'

grep  $SEARCH_TEXT $FILE > /dev/null

if [ $? -eq 0 ] ;
  then
        # Its found, so now use GNU sed to do inline replacement (-I) with backup. 
           
        #VERY IMPORTANT: using current time at part of backup extension tp safeguard backup
        current_time=`date +%k%M%S`
       
        sed -i.backup.${current_time} "/${SEARCH_TEXT}/ c\\${REPLACE_TEXT} " $FILE

  else
        echo "Not found. Adding a line" ;
        echo $REPLACE_TEXT >> $FILE 
fi


chrism01 09-09-2008 11:56 PM

rsync might be an idea for files whose contents you want to be the same everywhere.
Even if not, you can build a 'correct' set on a master box, then just loop/rsync them across. Might be simplest option.

chankle 09-10-2008 10:02 PM

That's an interesting idea. Yes, that would simplify things a lot.

chrism01 09-10-2008 11:13 PM

Actually used to work at a Merchant Bank where we used that system :)


All times are GMT -5. The time now is 03:38 AM.