Take the 2-minute tour ×
Ask Ubuntu is a question and answer site for Ubuntu users and developers. It's 100% free, no registration required.

When I copy any file and paste it in console or text editos it is passed as

file:///home/user/path/file

when I pass it to script it is not found

What is the easiest way to convert that to normal linux path or somehow make script support it?

for example

cat file:///home/user/path/file

says

No such file or directory

share|improve this question

4 Answers 4

up vote 0 down vote accepted

To remove the file:// prefix from the URL, you can use sed:

echo "file:///home/user/path/file" | sed "s/^file:\/\///g"

What the above does:

  • Displays the URL to the standard output (so it can be modified with sed)
  • Replaces all occurrences of file:// in any line that begins with file:// with nothing. This effectively removes file:// from the URL leaving only /home/user/path/file

To use this from a script you can try the following:

cat $(echo "file:///home/user/path/file" | sed "s/^file:\/\///g")

Now the error message is:

cat: /home/user/path/file: No such file or directory

(Please note that it refers to the correct filename instead of the URL.)

It would be much cleaner to store the converted filename in a shell variable and use it afterwards.

MYFILE=$(echo "file:///home/user/path/file" | sed "s/^file:\/\///g")
cat $MYFILE
share|improve this answer

I don't know of any commands that convert between file urls and file paths, but you can convert with python, or any other language with bindings to gio. E.g.:

$ python -c 'import gio,sys; print(gio.File(sys.argv[1]).get_path())' file:///home/user/path/file%20with%20spaces
/home/user/path/file with spaces
share|improve this answer
    
Thanks a bunch! Your command also works with umlauts, which is perfect for my use case. –  Glutanimate Dec 25 '12 at 2:06

I believe you can do this is bash itself. Try the following

echo "file:///home/user/path/file" | cut -d'/' -f3-
/home/user/path/file

It will delimit till file:// and the rest will be echoed on the terminal.

share|improve this answer
    
Nice, +1. However, cut is in no way part of bash. –  terdon Aug 1 '13 at 18:18
    
This will work incorrectly if the path doesn't start with file://, though. –  minerz029 Jan 11 at 1:36

You can use this, assuming file_path contains the path:

#!/bin/bash

file_path='file:///home/me/Desktop/path test'

file_path="${file_path#file://}"

echo "${file_path}"

which prints /home/me/Desktop/path test. This allows it to work with or without file://, using only Bash string manipulation.


You can add this to a function (in .bashrc) for ease of use:

Function:

norm_path() {
    echo "${@#file://}"
}

Usage:

cat "$(norm_path file:///home/user/path/file)"
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.