tags:

views:

41

answers:

3

use sed to replace every occurrence of /dir with $dir (replace / with $) in every script in a directory.

sed "s#/dir#$dir#g"

The $ keeps being interpreted as a function or variable call. Is there a way around this?

thanks

A: 

You can simply escape it with a backslash:

sed "s#/dir#\$dir#g"
Lukáš Lalinský
+1  A: 

Read your shell's friendly manual:

man sh

In the shell, "double quotes" around text allow variable interpretation inside, while 'single quotes' do not, a convention adopted by later languages such as Perl and PHP (but not e.g. JavaScript).

sed 's#/dir#$dir#g' *

To perform the replacement within the scripts do something like

find * -maxdepth 0 -type f | while read f; do  mv $f $f.old && sed 's#/dir#$dir#' $f.old > $f; done

or just

perl -pi.old -e 's#/dir#\$dir#' *  # Perl also interpolates variables in s commands
reinierpost
A: 

shell approach

for file in file*
do
  if [ -f "$file ];then
      while read -r line
        case "$line" in 
          */dir* ) line=${line///dir/\$dir}
        esac
        echo $line > temp    
      done < "file"
      mv temp $file
  fi
done
ghostdog74