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
1
  • 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 partmaps.org/era/unix/award.html Commented Nov 2, 2011 at 10:07

4 Answers 4

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.

Sign up to request clarification or add additional context in comments.

Comments

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)

Comments

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

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.