Ubuntu – How to make script support file:/// notation

bashscripts

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

Best Answer

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
Related Question