How to replace placeholder character or word in variable with value from another variable in Bash?

后端 未结 8 2104
死守一世寂寞
死守一世寂寞 2020-12-08 14:01

I\'m trying to write a simple Bash script. I have a simple \"template\" variable:

template = \"my*appserver\"

I then have a function (

8条回答
  •  悲哀的现实
    2020-12-08 14:19

    There are so many posts available online but the one which worked fine for me is as below.

    There are 2 ways to achieve this, if you want to replace a string (my old string is with special character :) with another string in a file, then use this:

    sed -i '/oldtext:/c\newtext: Rahul'  ./printName.txt
    

    Secondly, if you want to search for a string and then replace it with your variable, then do this:

    #here im concatinating two key + value(myvariable).
    firstkey="oldtext: old"
    
    key="newtext: "
    
    value=$(cat ./variableStoredHere.txt)
    
    key+=$value
    

    result for below command will be oldtext: old

    echo $firstkey 
    

    result for below command will be will be newtext: Rahul

    echo $key 
    
    
    sed -i "s/$firstkey/$key/g" ./printName.txt  
    

提交回复
热议问题