Replace a string in shell script using a variable

后端 未结 10 926
被撕碎了的回忆
被撕碎了的回忆 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:34
    echo $LINE | sed -e 's/12345678/'$replace'/g'
    

    you can still use single quotes, but you have to "open" them when you want the variable expanded at the right place. otherwise the string is taken "literally" (as @paxdiablo correctly stated, his answer is correct as well)

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

    Found a graceful solution.

    echo ${LINE//12345678/$replace}
    
    0 讨论(0)
  • 2020-11-22 05:45

    I prefer to use double quotes , as single quptes are very powerful as we used them if dont able to change anything inside it or can invoke the variable substituion .

    so use double quotes instaed.

    echo $LINE | sed -e "s/12345678/$replace/g"
    
    0 讨论(0)
  • 2020-11-22 05:46

    I had a similar requirement to this but my replace var contained an ampersand. Escaping the ampersand like this solved my problem:

    replace="salt & pepper"
    echo "pass the salt" | sed "s/salt/${replace/&/\&}/g"
    
    0 讨论(0)
  • 2020-11-22 05:48

    you can use the shell (bash/ksh).

    $ var="12345678abc"
    $ replace="test"
    $ echo ${var//12345678/$replace}
    testabc
    
    0 讨论(0)
  • 2020-11-22 05:53

    Single quotes are very strong. Once inside, there's nothing you can do to invoke variable substitution, until you leave. Use double quotes instead:

    echo $LINE | sed -e "s/12345678/$replace/g"
    
    0 讨论(0)
提交回复
热议问题