Flawed_Logicc Flawed_Logicc - 1 month ago 6
Bash Question

Bash Script: Replace backslash characters in argument?

I have a script called test and I am trying to take in an argument and replace backslashes with forward slashes. If I do the following:

#!/bin/bash

FIRST_ARGUMENT=$1

echo $FIRST_ARGUMENT | sed 's/\\/\//g'


And I use it in the following way:

$ ./test aaa\aa

aaaaa

My backslashes disappear. Is there a way to preserve them so they are replaced by sed? When I hardcode the path into a string within my echo call, as in:

echo 'aaa\aa'| sed 's/\\/\//g'


I get the proper result:

aaa/aa

Answer

While passing it to the ./test, use quote ' or " as:

./test 'aaa\aa'

Below is the example to show difference between content with quote and without quote:

moin@moin-pc:~$ echo aa\aa
aaaa  # without '\'
moin@moin-pc:~$ echo "aa\aa"
aa\aa  # with '\'

Also read: Meaning of backslash