1,105,585 Community Members

I can't get simple sed substitution to work.

Member Avatar
dancks
Junior Poster
149 posts since Nov 2010
Reputation Points: 4 [?]
Q&As Helped to Solve: 1 [?]
Skill Endorsements: 0 [?]
 
0
 

I made a website in php4 that I want to swtich over for my database, I'm a linux newb, I just thought I would write a simple sed script to change the username and password used in mysql_connect:

#!/bin/bash
for f in *
do
sed 's/mysql_connect(\'localhost\',\'user1\',\'pass1\')/mysql_connect(\'localhost\',\'user2\',\'pass2\')/' <$f >$f
done
exit 0

error:

./change: line 4: syntax error near unexpected token `)'

Also, someone mentioned that the script doesn't end? so I added exit 0, Ive only tried scripting once, over a year ago I don't remember ever doing that so if someone could elaborate that would be helpful.

Member Avatar
dancks
Junior Poster
149 posts since Nov 2010
Reputation Points: 4 [?]
Q&As Helped to Solve: 1 [?]
Skill Endorsements: 0 [?]
 
0
 

I wrote another script which I thnk comes closer to what I really wanted:

#!/bin/bash
for f in 'onestopshop/*'
do
echo "" | cat > tmp.txt
while read line
do
s=""
sed 's/user1/user2/'  < $line | sed 's/pass1/pass2/' > $s
if((${#s})>1)
do
cat $s >> tmp.txt
else
cat $line >> tmp.txt
fi
done < $f
cp ((onestopshop/$f)) tmp.txt
done
exit 0

where it checks for a pattern match before writing the line to tmp.txt, and writing the modified line if a match was found.

Member Avatar
dancks
Junior Poster
149 posts since Nov 2010
Reputation Points: 4 [?]
Q&As Helped to Solve: 1 [?]
Skill Endorsements: 0 [?]
 
0
 

Now this is the final working solution:

#!/bin/bash
if [ ! -e backup ]
then
    mkdir backup
fi
for f in *
do
    if [ "$f" != "change" ]
    then
        if [ ! -d $f ]
        then
            cp $f backup/$f
            sed -i 's/user1/user2/g' $f
            sed -i 's/pass1/pass2/g' $f
        fi
    fi
done
exit 0

Except the if statement [ "$f" != "change" ] didn't protect the script from being changed itself. oops.

Question Self-Answered as of 1 Year Ago
You
This question has already been solved: Start a new discussion instead
Post:
Start New Discussion
Tags Related to this Article