Take the 2-minute tour ×
Super User is a question and answer site for computer enthusiasts and power users. It's 100% free, no registration required.

I am trying to use the stream editor sed in bash to replace a string in a file to a new string that I entered, I have this thus far:

echo "name to change"
read updatenaamold
echo "enter new name:"
read updatenaamnew
sed -i 's/$updatenaamold/$updatenaamnew/g' $naam_dir
echo "name changed"

This should work! But it doesn't somehow, in the file that I want to edit there is a name called "bryan" I want to edit it to "bryan name". I've put the old name in a variable that i need to enter obviously, and the new name in a variable aswell. Can someone point out to me why it doesn't work?

share|improve this question
    
Could you use a better code formatting? I'm having trouble understanding the code. (Ok, I'm trying by viewing source code of the page) –  LatinSuD Jun 3 '11 at 13:14

2 Answers 2

Just use double quote instead of single quote. (Single quotes don't allow variable expansion).

echo "name to change"
read updatenaamold
echo "enter new name:"
read updatenaamnew
sed -i "s/$updatenaamold/$updatenaamnew/g" $naam_dir
echo "name changed"

Note 1: If $naam_dir is a directory it won't work either. Afaik sed works on a file-by-file basis.

Note 2: If user enters special characters (like: / ^ $ [] ) things won't work as expected, because it will confuse sed. Workaround (not sure if this would be the best way):

updatenaamold=$( POSIXLY_CORRECT=1 /bin/echo "$updatenaamold" | sed 's/[^a-zA-Z0-9]//g' )
updatenaamnew=$( POSIXLY_CORRECT=1 /bin/echo "$updatenaamnew" | sed 's/[^a-zA-Z0-9]//g' )

Add it before sed. It will remove characters that are other than letters and numbers (no spaces, no international chars, etc). Another approach would be aborting when found weird chars (and prevent accidental errors).

share|improve this answer
    
Hmm I see, I changed it and it works! Note1: Is there a way to get around sed crashing when entereing things like (\ ^ [] &) like you said? –  bryan Jun 3 '11 at 13:39
    
Thanks LatinSuD, I will try to add this to my script when I get home. Can you explain the lines after Note2 for me :)? I would like to fully understand what it does before I implement it. Thanks again! –  bryan Jun 3 '11 at 15:32

Since you're using bash I'd suggest using checking out bash string manipulations.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.