Replace String in variable using bash

Viewed 9144

I'd like to replace a string within a variable, so e.g.

Test=Today, 12:34

I'd like to replace the "Today" within the variable Test with a Date variable I declared before.

I tried using the "-sed" command,

sed -i -e "s/Today/$Date" '$Test'

but it would just print out an error and the file '$Test' is not known. So using sed is only possible using text files?

Kind regards, X3nion

2 Answers

First, that's a syntax error.

$: Test=Today, 12:34
bash: 12:34: command not found

Put some quoting on it.

$: Test="Today, 12:34"
$: Test='Today, 12:34'
$: Test=Today,\ 12:34

Then you can just use built-n bash parameter parsing.

$: Test='Today, 12:34'
$: Date=12.12.2000
$: Test="${Test/Today/$Date}"
$: echo "$Test"
12.12.2000, 12:34

This works for me:

Test="Today, 12:34"
Date=12.12.2000
sed 's/Today/'"$Date"'/g' <<<"$Test"

Edit: If you would like to change the variable Test, like mentioned in the comment, you need the assignment:

Test="Today, 12:34"
Date=12.12.2000
Test=$(sed 's/Today/'"$Date"'/g' <<<"$Test")
Related