Home > front end >  bash insert a string variable to a string(another variable) at specific location
bash insert a string variable to a string(another variable) at specific location

Time:11-30

I have these 2 variables

to_insert="John"
full_string="My name is and I am 25 years old"

I would like to insert the value of "to_insert" into "full_string" after the word/string "is". Basically I want to get this in the end:

full_string="My name is John and I am 25 years old"

would appreciate your help, Alon

CodePudding user response:

You can simply expand the 'to_insert' variable inside 'full_string' like this:

full_string="My name is $to_insert and I am 25 years old"

CodePudding user response:

Use Parameter Expansion - Substitution:

#! /bin/bash
to_insert="John"
full_string="My name is and I am 25 years old"
echo "${full_string/ is / is "$to_insert" }"

CodePudding user response:

You can use bash to search for "is" and replace it with "is $to_insert":

to_insert="John"
full_string="My name is and I am 25 years old"
full_string=${full_string/is/is $to_insert}
echo $full_string

Output:

My name is John and I am 25 years old

Reference: Search for "${parameter/pattern/string}" in https://www.gnu.org/software/bash/manual/html_node/Shell-Parameter-Expansion.html

CodePudding user response:

Using sed

$ sed "s/\(.*is\)/\1 $to_insert/" <<< "$full_string"
My name is John and I am 25 years old

CodePudding user response:

to_insert='John'
full_string='My name is and I am 25 years old'
prefix='My name is'

even_fuller_string="${full_string::${#prefix}} ${to_insert} ${full_string:${#prefix}   1}"
echo "$even_fuller_string"
  •  Tags:  
  • bash
  • Related