-   Linux - Newbie (
-   -   bash script to create text in a file or replace value of text if already exists (

knightto 09-09-2008 10: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

That should help.

Thanks in advance

chrism01 09-09-2008 09: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.

Actually, this is exactly the sort of issue Perl was originally designed for. There's even an O'Reilly book: (Perl for System Admin)

chankle 09-10-2008 12:50 AM

Hi, here's what I came up with:


REPLACE_TEXT="net.ipv4.ip_forward = some_other_value"

grep  $SEARCH_TEXT $FILE > /dev/null

if [ $? -eq 0 ] ;
        # 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

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

chrism01 09-10-2008 12:56 AM

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 11:02 PM

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

chrism01 09-11-2008 12:13 AM

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

All times are GMT -5. The time now is 01:12 AM.