Changing a forward slash to another character in bash

Changing a forward slash to another character in bash

If you find yourself needing to replace a forward slash character, for instance, in a path, with another character, you can use the code snippet below. 

This script replaces a forward slash with an underscore in a hard coded string:

new_var=$(echo "/path/to/directory" | sed -e 's///_/g')

This script replaces a forward slash with an underscore in an argument passed into a function or into a script:

new_var=$(echo $1 | sed -e 's///_/g')

This script replaces a forward slash with an underscore in a previously defined variable.

new_var=$(echo $orig_var | sed -e 's///_/g')

To replace the underscore with something different, change ‘s///_/g’ to replace the underscore with something else. For example, to instead use a dash, use ‘s///-/g’

Like so:

new_var=$(echo $orig_var | sed -e 's///-/g')