如何制作脚本支持文件:///表示法?
当我复制任何文件并将其粘贴到控制台或文本编辑器中时,它将作为传递
文件:/// home / user中/路径/文件
当我把它传递给脚本时,它找不到
什么是将其转换为普通linux路径或以某种方式使脚本支持它的最简单方法?
例如
cat file:/// home / user / path / file
说
没有相应的文件和目录
要从URL中删除file://
前缀,可以使用sed :
echo "file:///home/user/path/file" | sed "s/^file:\/\///g"
以上是做什么的:
- 显示标准输出的URL(因此可以使用sed修改)
- 在任何以
file://
开头的行中替换所有出现的file://
。 这有效地从URL中删除了file://
,只留下/home/user/path/file
要从脚本中使用此function,您可以尝试以下操作:
cat $(echo "file:///home/user/path/file" | sed "s/^file:\/\///g")
现在错误消息是:
cat: /home/user/path/file: No such file or directory
(请注意,它指的是正确的文件名而不是URL。)
将转换后的文件名存储在shell变量中并在之后使用它会更加清晰。
MYFILE=$(echo "file:///home/user/path/file" | sed "s/^file:\/\///g") cat $MYFILE
我不知道在文件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
我相信你能做到这一点就是bash本身。 请尝试以下方法
echo "file:///home/user/path/file" | cut -d'/' -f3- /home/user/path/file
它将分隔到file: //
,其余的将在终端上回显。
您可以使用此方法,假设file_path
包含路径:
#!/bin/bash file_path='file:///home/me/Desktop/path test' file_path="${file_path#file://}" echo "${file_path}"
打印/home/me/Desktop/path test
。 这允许它使用或不使用file://
,仅使用Bash字符串操作。
您可以将其添加到函数(在.bashrc
)以便于使用:
function:
norm_path() { echo "${@#file://}" }
用法:
cat "$(norm_path file:///home/user/path/file)"
你也可以使用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
如果您不需要hex支持,则可以使用cut -c 8-
。 或者,你可以使用urlencode和任何其他删除file://
方法file://
(sed,大括号扩展等)