1

I'd like to replace all slashes from a web address.

Example address: https://example.com/sub/folder/files/file.txt

Expected result: example.com-sub-folder-files-file.txt

I can strip the https but I seem unable to replace the remaining slashes with:

echo $(echo 'https://example.com/sub/folder/files/file.txt' | sed 's/http[s]*:\/\///')

The above only gives me this:

example.com/sub/folder/files/file.txt

Adding a second sed to replace slashes only removes the first encountered. What am I doing wrong?

2 Answers2

1

You don't need double echo.

I don't understand what you mean by Adding a second sed to replace slashes only removes the first encountered. - you only have one sed command in your example. You can easily do what you want with 2 sed commands like that:

echo 'https://example.com/sub/folder/files/file.txt' | sed 's,http[s]*:\/\/,,;s,/,-,g'
  • The double echo is just for the example, it was indeed not necessary. In my script I use it to set a variable. The g for global is what I missed. – stargazer Apr 02 '18 at 06:17
1

try this:

echo "https://www.example.com/sub/folder/files/file.txt" | sed -e 's#http[s]://##' -e 's#/#-#g'

result is: www.example.com-sub-folder-files-file.txt

the reason it was only replacing the 'first encountered' is because you were missing the g as the last 'parameter' passed to sed, it stands for global and will replace all instances found with the desired replacement, without it, it will replace only the first instance found.

Also its worth noting that you can seperate the parameters of the sed command with any symbol, it doesnt need to be '/' , I prefer to use a symbol not involved in the search and replace at all, as it will save you some overthinking with eascaping characters, and potential bug when you are replacing /.

Also, you can string together a few commands in sed by using the -e option, as you can see above, I replaced 'https://' with nothing ( removing it ) , then replaced all '/' with '-'. easy easy.

Hope it helps you

  • That helped, I missed the g for global. Thanks a lot! I accept yours as answer for readability in the sed pipe. – stargazer Apr 02 '18 at 06:19