I'd like to replace a string within a variable, 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. Is using sed only possible with text files?
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 bash's built-in parameter expansion:
$: 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")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With