jm_
jm_

Reputation: 641

Howto use a blank space as a variable with SED

I need to replace "a" by " " (single space) in a file, being " " (single space) a variable. I don't get it. Following command doesn't work:

SRC="a" DST=" "; sed -i 's/'$SRC'/'$DST'/g' test.txt

I tried '\ ', "\ ", ' ', etc without success.

Thanks,

Upvotes: 0

Views: 159

Answers (2)

Kent
Kent

Reputation: 195269

can you try this?

$SRC="a" DST=" "; sed -i "s/$SRC/$DST/g" test.txt

shell var would be expanded between double quote .

Upvotes: 1

William Pursell
William Pursell

Reputation: 212654

sed -i 's/'$SRC'/'$DST'/g' test.txt

is exactly the same as:

sed -i 's/a/' '/g' test.txt

so you are passing two distinct arguments to sed. You could do:

sed -i "s/$SRC/$DST/g" test.txt

but if you insist on using sed it's probably better to do:

sed -i "y/$SRC/$DST/" test.txt

Upvotes: 3

Related Questions