[SOLVED] Way to replace one variable with another in a string

Issue

I need to replace one variable with another variable in a multiple strings.
For example:

string1="One,two" 
string2="three.four" 
string3="five:six"
y=";"
for str in string1 string2 string3; do
    x="$(echo "$str" | sed 's/[a-zA-Z]//g')" # extracting a character between letters
    sed 's/$x/$y/'$str # I tried this, but it does not work at all.
    echo "$str"
done

Expecting output:

One;two
three;four
five;six

In my output, nothing changes:

One,two
three.four
five:six

Solution

You can use bash’s substitution operator instead of sed. And simply replace anything that isn’t a letter with $y.

#!/bin/bash

string1="One,two"
string2="three.four"
string3="five:six"
y=";"

for str in "$string1" "$string2" "$string3"; do
    x=${str//[^a-zA-Z]+/$y}
    echo "$x"
done

Output is:

One;two
three;four
five;six

Note that your general approach wouldn’t work if the input string has muliple delimiters, e.g. One,two,three. When you remove all the letters you get ,,, but that doesn’t appear anywhere in the string.

Answered By – Barmar

Answer Checked By – Willingham (BugsFixing Volunteer)

Leave a Reply

Your email address will not be published.