-3

I tried: $ echo $HOME | sed 's/$HOME/~/g

but this didn't work, perhaps because of forward slashes?

Does anyone have a script to do this either or:

  • using bash builtins
  • using sed

Thank you

Nick
  • 195

1 Answers1

3

A couple things are preventing your command from working.

First, bash will never perform variable expansion (nor command expansion, etc.) inside single quotes. You'll need to use double quotes.

Also, it is highly likely that $HOME contains at least one slash, so using the slash symbol in your sed command as the delimiter between the target and replacement strings means you need to escape any slashes present in $HOME:

$ echo $HOME | sed "s/${HOME//\//\\\/}/~/"
~

Responding to your comment below, yes, you can also use bash's string variable operators to accomplish this, and somewhat more concisely at that:

$ echo $A
/home/jim/screenshot.png
$ echo "${A/$HOME/\~}" 
~/screenshot.png
Jim L.
  • 7,997
  • 1
  • 13
  • 27