Guru N
Guru N

Reputation: 75

how to replace string with '$' in unix using sed

I'm trying to replace string ######### to $ in all files in $HOME/findreplace/ directory with below statements but I'm getting sed: Function s_#########_ cannot be parsed. error.

Thanks in advance for you help.

for file in $HOME/findreplace/*.*
do
    sed -e "s_#########_$_g" $file> /tmp/tempfile.tmp
    mv /tmp/tempfile.tmp $file
    echo "Modified: " $file
done

Upvotes: 1

Views: 714

Answers (1)

sampson-chen
sampson-chen

Reputation: 47267

You can do:

for file in $HOME/findreplace/*.*
do
    sed -i 's/#########/\$/g' "$file"
    echo "Modified:  $file"
done

Explanation:

  • Use / instead where you had _ before to separate the pattern to match and pattern to replace.
  • Use \ to escape the $ char
  • Use single quotes instead of double quotes to avoid having bash auto-expand something (string enclosed by single quotes will be interpreted literally)
  • Use the -i option to sed to do in-place editing, so you can avoid having to use a temp file.
  • You almost always want to enclose your variables (such as $file) in double-quotes.

Upvotes: 2

Related Questions