5

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

UAdapter
  • 17,967

5 Answers5

6

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
geirha
  • 47,279
1

You can also use urlencode (sudo apt-get gridsite-clients):

$ echo "$(urlencode -d "file:///folder/with%20spaces")"
file:///folder/with spaces
$ echo "$(urlencode -d "file:///folder/with%20spaces"|cut -c 8-)"
/folder/with spaces

If you don't need hexadecimal support, you can just use cut -c 8-. Alternatively, you could use urlencode with any other method of removing the file:// (sed, brace expansion, etc.)

wroth
  • 11
0

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.

Mitch
  • 109,787
0

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)"
kiri
  • 28,986
0

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
lgarzo
  • 20,492