如何使脚本支持 file:/// 符号?

UAd*_*ter 5 bash scripts

当我复制任何文件并将其粘贴到控制台或文本编辑器中时,它会作为

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

当我将它传递给脚本时找不到它

将其转换为普通 linux 路径或以某种方式使脚本支持它的最简单方法是什么?

例如

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

无此文件或目录

gei*_*rha 6

我不知道在文件 url 和文件路径之间转换的任何命令,但您可以使用 python 或任何其他绑定到 gio 的语言进行转换。例如:

$ 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
Run Code Online (Sandbox Code Playgroud)


lga*_*rzo 0

file://要从 URL 中删除前缀,您可以使用sed

echo "file:///home/user/path/file" | sed "s/^file:\/\///g"
Run Code Online (Sandbox Code Playgroud)

上面的作用是:

  • 显示标准输出的 URL(因此可以使用 sed 修改)
  • file://替换任何以空开头的行中所有出现的file://file://这有效地从 URL 中删除,只留下/home/user/path/file

要从脚本中使用它,您可以尝试以下操作:

cat $(echo "file:///home/user/path/file" | sed "s/^file:\/\///g")
Run Code Online (Sandbox Code Playgroud)

现在错误信息是:

cat: /home/user/path/file: No such file or directory
Run Code Online (Sandbox Code Playgroud)

(请注意,它指的是正确的文件名而不是 URL。)

将转换后的文件名存储在 shell 变量中并随后使用它会更清晰。

MYFILE=$(echo "file:///home/user/path/file" | sed "s/^file:\/\///g")
cat $MYFILE
Run Code Online (Sandbox Code Playgroud)