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

后端 未结 8 1959
死守一世寂寞
死守一世寂寞 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:23

    Yeah, either 'sed' as the others have said, or start with your template in 2 separate variables and construct on the fly. e.g.

    templateprefix="my"
    templatesuffix="appserver"
    
    server=get_env
    
    template=${templateprefix}${server}${templatesuffix}
    
    0 讨论(0)
  • 2020-12-08 14:26

    Here's a bash script that wraps this up

    Example:

    $ search_and_replace.sh "test me out" "test me" ez
    ez out
    

    search_and_replace.sh

    #!/bin/bash
    function show_help()
    {
      echo ""
      echo "usage: SUBJECT SEARCH_FOR REPLACE_WITH"
      echo ""
      echo "e.g. "
      echo ""
      echo "test t a                     => aesa"
      echo "'test me out' 'test me' ez   => ez out"
      echo ""
    
      exit
    }
    
    if [ "$1" == "help" ]
    then
      show_help
      exit
    fi
    if [ -z "$3" ]
    then
      show_help
      exit
    fi
    
    SUBJECT=$1
    SEARCH_FOR=$2
    REPLACE_WITH=$3
    
    echo "$SUBJECT" | sed -e "s/$SEARCH_FOR/$REPLACE_WITH/g"
    
    0 讨论(0)
提交回复
热议问题