4

I have a large number of words in a text file to replace.

This script is working up until the sed command where I get:

sed: 1: "*.js": invalid command code *

PS... Bash isn't one of my strong points - this doesn't need to be pretty or efficient

cd '/Users/xxxxxx/Sites/xxxxxx'
    echo `pwd`;

    for line in `cat myFile.txt`
    do
        export IFS=":"
        i=0
        list=()

        for word in $line; do
            list[$i]=$word
            i=$[i+1]
        done

        echo ${list[0]}
        echo ${list[1]}

        sed -i "s/{$list[0]}/{$list[1]}/g" *.js

    done
James Zaghini
  • 3,895
  • 4
  • 45
  • 61
  • 2
    As a matter of style, `echo \`pwd\`` is a Useless Use of Echo; just `pwd` will print the current working directory. Similarly, running a `for` loop over `cat` in backticks is a Useless Use of Cat. See also http://partmaps.org/era/unix/award.html – tripleee Nov 02 '11 at 10:07

4 Answers4

3

You're running BSD sed (under OS X), therefore the -i flag requires an argument specifying what you want the suffix to be.

Also, no files match the glob *.js.

Ignacio Vazquez-Abrams
  • 776,304
  • 153
  • 1,341
  • 1,358
2

This looks like a simple typo:

sed -i "s/{$list[0]}/{$list[1]}/g" *.js

Should be:

sed -i "s/${list[0]}/${list[1]}/g" *.js

(just like the echo lines above)

johnsyweb
  • 136,902
  • 23
  • 188
  • 247
1

So myFile.txt contains a list of from:to substitutions, and you are looping over each of those. Why don't you create a sed script from this file instead?

cd '/Users/xxxxxx/Sites/xxxxxx'
sed -e 's/^/s:/' -e 's/$/:/' myFile.txt |
# Output from first sed script is a sed script!
# It contains substitutions like this:
# s:from:to:
# s:other:substitute:
sed -f - -i~ *.js

Your sed might not like the -f - which means sed should read its script from standard input. If that is the case, perhaps you can create a temporary script like this instead;

sed -e 's/^/s:/' -e 's/$/:/' myFile.txt >script.sed
sed -f script.sed -i~ *.js
tripleee
  • 175,061
  • 34
  • 275
  • 318
0

Another approach, if you don't feel very confident with sed and think you are going to forget in a week what the meaning of that voodoo symbols is, could be using IFS in a more efficient way:

IFS=":"
cat myFile.txt | while read PATTERN REPLACEMENT  # You feed the while loop with stdout lines and read fields separated by ":"
do
   sed -i "s/${PATTERN}/${REPLACEMENT}/g"
done

The only pitfall I can see (it may be more) is that if whether PATTERN or REPLACEMENT contain a slash (/) they are going to destroy your sed expression. You can change the sed separator with a non-printable character and you should be safe. Anyway, if you know whats on your myFile.txt you can just use any.

javiunzu
  • 56
  • 4