I have a Windows path in a bash variable as a string:

file='C:\Users\abcd\Downloads\testingFile.log' 

I am trying to convert this path into a Linux path starting with /c/Users....

My attempt

The following works:

file=${file/C://c} file=${file//\\//} echo $file > /c/Users/abcd/Downloads/testingFile.log 

Problem

Here, I have done this for a string that contains the filepath. The reason I am asking this question is that I have to convert 20 such strings in a bash script in Ubuntu 16.04 and each time I do this I have to write 2 lines per conversion - it is taking up a lot of space!

Question

Is there a way to combine the 2 commands

file=${file/C://c} file=${file//\\//} 

into one command?

2

4 Answers

There would be a way to do both replacements at once using sed, but it's not necessary.

Here's how I would solve this problem:

  1. Put filenames in array
  2. Iterate over array
filenames=( 'C:\Users\abcd\Downloads\testingFile.log' # ... add more here ... ) for f in "${filenames[@]}"; do f="${f/C://c}" f="${f//\\//}" echo "$f" done 

If you want to put the output into an array instead of printing, replace the echo line with an assignment:

 filenames_out+=( "$f" ) 
4

If it's something you want to do many times, then why not create a little shell function?

win2lin () { f="${1/C://c}"; printf '%s\n' "${f//\\//}"; } $ file='C:\Users\abcd\Downloads\testingFile.log' $ win2lin "$file" /c/Users/abcd/Downloads/testingFile.log $ $ file='C:\Users\pqrs\Documents\foobar' $ win2lin "$file" /c/Users/pqrs/Documents/foobar 
3

You would be able to achieve this in one line using sed

file="$(echo "$file" | sed -r -e 's|^C:|/c|' -e 's|\\|/|g')" 

Note the two patterns must remain separate nonetheless as the matches are replaced by different substitutions.

1

Is this question still open to new suggestions? If so, would this help you?

$ file="/$(echo 'C:\Users\abcd\Downloads\testingFile.log'|tr '\\' '/')" $ echo $file /C:/Users/abcd/Downloads/testingFile.log 

Oh, and in case the C must be cast to lowercase:

file="/$(echo 'C:\Users\abcd\Downloads\testingFile.log'|tr '^C' 'c'|tr '\\' '/')" 

As an overview:

$ file='C:\Users\abcd\Downloads\testingFile.log' $ echo $file C:\Users\abcd\Downloads\testingFile.log $ file="/$(echo $file|tr '^C' 'c'|tr '\\' '/')" $ echo $file /c:/Users/abcd/Downloads/testingFile.log 
4

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy