Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace string in variable using Bash

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?

like image 498
X3nion Avatar asked Jan 24 '26 00:01

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 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
like image 101
Paul Hodges Avatar answered Jan 25 '26 22:01

Paul Hodges


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")
like image 23
TheSlater Avatar answered Jan 25 '26 20:01

TheSlater



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!