Bash script to convert windows path to linux path

15,280

Solution 1

You need to catch the variable and then process it.

For example this would make it:

function cdwin(){
    echo "I receive the variable --> $1"
    line=$(sed -e 's#^J:##' -e 's#\\#/#g' <<< "$1")
    cd "$line"
}

And then you call it with

cdwin "J:\abc\def"

Explanation

The command

line=$(sed -e 's#^J:##' -e 's#\\#/#g' <<< "$1")

is equivalent to

line=$(echo $1 | sed -e 's#^J:##' -e 's#\\#/#g')

and replaces every \ with /, saving the result into the var line. Note it uses another delimiter, #, to make it more readable. It also removes the leading J:.

Solution 2

sed allows alternative delimiters so better to not to use /.

Try this sed command:

sed -e 's~\\~/~g' -e 's~J:~/usr~' <<< "$line"

Solution 3

You don't even need to use sed (although there's nothing wrong with using sed). This works for me using bash string substitution:

function cdwin() {
  line=${1/J://usr}
  line=${line//\\//}
  cd "$line"
}

cdwin 'J:\abc\def'

Substitution works as follows (simplification):

${var/find/replace} 

and double slash means replace all:

${var//findall/replace}

In argument 1, replace the first instance of J: with /usr:

${1/J://usr}

In variable line replace all (//) backslashes (escaped, \\) with (/) forwardslash (/):

${line//\\//}

echo the output of any of those to see how they work

Share:
15,280
user2987193
Author by

user2987193

Updated on June 12, 2022

Comments

  • user2987193
    user2987193 almost 2 years

    I'm new to shell scripting and trying to accomplish following, converting a windows path to a linux path and navigating to that location:

    Input: cdwin "J:\abc\def" Action: cd /usr/abc/def/

    So, I'm changing the following:

    "J:" -> "/usr"
    

    and

    "\" -> "/"
    

    This is my try, but it doesn't work. It just returns a blank if i echo it:

    function cdwin(){
        line="/usrfem/Projects$1/" | sed 's/\\/\//g' | sed 's/J://'
        cd $line
    }