Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

template = "my*appserver" 

I then have a function (get_env()) that returns the values dev, qa, or live. I'd like to call get_env and then string-replace the template variable with get_env's return value and swap it out with the asterisk. So:

# Returns "dev" server = get_env  # Prints "mydevappserver" template = string_replace(server, template) 

Or:

# This time, it returns "live" server = get_env  # Prints "myliveappserver" template = string_replace(server, template) 

What should I be using in lieu of this string_replace() function to accomplish the binding?

like image 846
IAmYourFaja Avatar asked Dec 04 '12 19:12

IAmYourFaja


People also ask

How do you replace a word with another word in bash?

The 'sed' command is used to replace any string in a file using a bash script. This command can be used in various ways to replace the content of a file in bash. The 'awk' command can also be used to replace the string in a file.

How do I replace a variable in bash?

To replace a substring with new value in a string in Bash Script, we can use sed command. sed stands for stream editor and can be used for find and replace operation. We can specify to sed command whether to replace the first occurrence or all occurrences of the substring in the string.

What does [- Z $1 mean in bash?

$1 means an input argument and -z means non-defined or empty. You're testing whether an input argument to the script was defined when running the script. Follow this answer to receive notifications.

What does %% do in bash?

In your case ## and %% are operators that extract part of the string. ## deletes longest match of defined substring starting at the start of given string. %% does the same, except it starts from back of the string.


2 Answers

Bash can do string replacement by itself:

template='my*appserver' server='live' template="${template/\*/$server}" 

See the advanced bash scripting guide for more details on string replacement.

So for a bash function:

function string_replace {     echo "${1/\*/$2}" } 

And to use:

template=$(string_replace "$template" "$server") 
like image 151
Spencer Rathbun Avatar answered Sep 24 '22 00:09

Spencer Rathbun


String replacement in a bash-script can e.g. be achieved by sed:

template=$(echo $template | sed 's/old_string/new_string/g') 

This will replace old_string with new_string in the template variable.

like image 26
sge Avatar answered Sep 27 '22 00:09

sge