3

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?

1
  • 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, 2011 at 13:14

2 Answers 2

6

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).

2
  • 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, 2011 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, 2011 at 15:32
1

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

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .