0

I have a string like "/directory/username" and I want to use a bash script to change this to "/directory-username". This is what I have tried:

path="/directory/username"
path=$($path | sed -r 's/(.*)\//\1-/')

Here is the output:

bash: /directory/username: No such file or directory

What is it that I have failed to understand?

James Newton
  • 6,623
  • 8
  • 49
  • 113
  • The thing before `|` needs to be a *command,* not just the data you want to feed into the pipe. This is a common beginner error. (The [lack of quotes](https://stackoverflow.com/questions/10067266/when-to-wrap-quotes-around-a-shell-variable) is another.) – tripleee Jun 17 '21 at 06:32

1 Answers1

0

$path will execute as a command in your expression.

Try path=$(echo "$path" | sed -r 's/(.*)\//\1-/') to treat $path as a parameter.

There is no need to escape the pattern split character. To make the command more elegant, you could use # to replace / as the pattern split character in this case, like path=$(echo "$path" | sed -r 's#(.*)/#\1-#')

James Newton
  • 6,623
  • 8
  • 49
  • 113
Victor Lee
  • 2,467
  • 3
  • 19
  • 37
  • 2
    You should double-quote variable references to avoid weird parsing problems, e.g. `echo "$path"` instead of just `echo $path`. – Gordon Davisson Jun 17 '21 at 06:47