using sed to find and replace in bash for loop

前端 未结 4 1977
一生所求
一生所求 2021-01-06 15:21

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\": inval

相关标签:
4条回答
  • 2021-01-06 15:35

    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.

    0 讨论(0)
  • 2021-01-06 15:40

    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)

    0 讨论(0)
  • 2021-01-06 15:44

    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.

    0 讨论(0)
  • 2021-01-06 15:46

    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
    
    0 讨论(0)
提交回复
热议问题