X3nion
X3nion

Reputation: 301

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?

Upvotes: 14

Views: 25256

Answers (4)

exactzen
exactzen

Reputation: 1

It's very important to test :

input="a\b\c\d"
echo ${input}
echo "${input/\\//}"
echo "${input//\\//}"

Note that : only the last echo with '//', not '/', to begin, give us global replace !!

Upvotes: 0

Paul Hodges
Paul Hodges

Reputation: 15246

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

Upvotes: 13

Xander Harris
Xander Harris

Reputation: 63

To do this you don't need to make any use of sed and can, instead, make use of the little-known, but extremely handy feature of Bash called parameter expansion described here. I only know about this because it came up in a job interview once and the interviewer shared it with me then left me to clean my brains up off the floor...

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

As I said, this blew my mind in that job interview. I didn't get the job, but I've used this feature just about every day since.

Upvotes: 6

TheSlater
TheSlater

Reputation: 660

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

Upvotes: 8

Related Questions