Replace a string in shell script using a variable

后端 未结 10 927
被撕碎了的回忆
被撕碎了的回忆 2020-11-22 05:18

I am using the below code for replacing a string inside a shell script.

echo $LINE | sed -e \'s/12345678/\"$replace\"/g\'

but it\'s getting

相关标签:
10条回答
  • 2020-11-22 05:53

    To let your shell expand the variable, you need to use double-quotes like

    sed -i "s#12345678#$replace#g" file.txt
    

    This will break if $replace contain special sed characters (#, \). But you can preprocess $replace to quote them:

    replace_quoted=$(printf '%s' "$replace" | sed 's/[#\]/\\\0/g')
    sed -i "s#12345678#$replace_quoted#g" file.txt
    
    0 讨论(0)
  • 2020-11-22 05:54

    Not specific to the question, but for folks who need the same kind of functionality expanded for clarity from previous answers:

    # create some variables
    str="someFileName.foo"
    find=".foo"
    replace=".bar"
    # notice the the str isn't prefixed with $
    #    this is just how this feature works :/
    result=${str//$find/$replace}
    echo $result    
    # result is: someFileName.bar
    
    str="someFileName.sally"
    find=".foo"
    replace=".bar"
    result=${str//$find/$replace}
    echo $result    
    # result is: someFileName.sally because ".foo" was not found
    
    0 讨论(0)
  • 2020-11-22 05:54

    Use this instead

    echo $LINE | sed -e 's/12345678/$replace/g'
    

    this works for me just simply remove the quotes

    0 讨论(0)
  • 2020-11-22 05:58

    If you want to interpret $replace, you should not use single quotes since they prevent variable substitution.

    Try:

    echo $LINE | sed -e "s/12345678/\"${replace}\"/g"
    

    assuming you want the quotes put in. If you don't want the quotes, use:

    echo $LINE | sed -e "s/12345678/${replace}/g"
    

    Transcript:

    pax> export replace=987654321
    pax> echo X123456789X | sed "s/123456789/${replace}/"
    X987654321X
    pax> _
    

    Just be careful to ensure that ${replace} doesn't have any characters of significance to sed (like / for instance) since it will cause confusion unless escaped. But if, as you say, you're replacing one number with another, that shouldn't be a problem.

    0 讨论(0)
提交回复
热议问题