Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bash script to convert windows path to linux path

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
}
like image 766
user2987193 Avatar asked Nov 15 '13 11:11

user2987193


People also ask

What is Cygpath?

The cygpath program is a utility that converts Windows native filenames to Cygwin POSIX-style pathnames and vice versa. It can be used when a Cygwin program needs to pass a file name to a native Windows program, or expects to get a file name from a native Windows program.

How do I get the PATH of a bash script?

In bash, there are a number of ways of retrieving the full address of a script. In particular, we can use realpath, readlink, or even create our custom little script. When we want to know the directory path, we can use the dirname command in our bash script to retrieve our directory path.

What is bash PATH?

PATH variable This is the variable that tells the bash shell where to find different executable files and scripts. The shell will check the directories listed in the PATH variable for the script you are trying to find.


2 Answers

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:.

like image 139
fedorqui 'SO stop harming' Avatar answered Oct 01 '22 08:10

fedorqui 'SO stop harming'


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

Try this sed command:

sed -e 's~\\~/~g' -e 's~J:~/usr~' <<< "$line"
like image 32
anubhava Avatar answered Oct 01 '22 07:10

anubhava