0

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

1
  • You should add an anchor to full_string, something along the lines of full_string='My name is #{NAME} and I am 25 years old'; full_string="${full_string/"#{NAME}"/John}" Commented Nov 29, 2021 at 16:24

4 Answers 4

1

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" }"
Sign up to request clarification or add additional context in comments.

Comments

1
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"

Comments

0

Using sed

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

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.