Linux 以与 Bash 相同的方式转义文件名

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5608112/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-05 03:36:00  来源:igfitidea点击:

Escape filenames the same way Bash does it

linuxbashescaping

提问by M.A.G

When I use the "tab" key in bash(when you have started to type the filename and you want it to complete), bashescapes the filename correctly, and if I use exactly that "escaped" filename, it works.

当我使用“tab”键时bash(当您开始输入文件名并希望它完成时),bash正确转义文件名,如果我完全使用“转义”文件名,它就可以工作。

For Instance:

例如:

An-Beat - Mentally Insine (Original Mix).mp3=> After bashEscapes It Using "TAB" An-Beat\ -\ Mentally\ Insine\ \(Original\ Mix\).mp3

An-Beat - Mentally Insine (Original Mix).mp3=>bash使用“TAB”转义 后An-Beat\ -\ Mentally\ Insine\ \(Original\ Mix\).mp3

I'm search for a function for bashthat will escape a filename the same way "tab" escapes filenames.

我正在寻找一个函数,bash它可以像“tab”转义文件名一样转义文件名。

回答by kurumi

$ string="An-Beat - Mentally Insine (Original Mix).mp3"
$ echo ${string// /\ }
An-Beat\ -\ Mentally\ Insine\ (Original\ Mix).mp3
$ string=${string// /\ }
$ echo ${string//(/\( }
An-Beat - Mentally Insine \( Original Mix).mp3

回答by sehe

Use printf(1):

使用printf(1):

x='a real \good %* load of c$rap'
x=$(printf '%q' "$x")
echo $x

will return

将返回

a\ real\ \good\ %\*\ load\ of\ c$rap

回答by bvarner

I'm going to elaborate on sehe's response on this one.

我将详细说明sehe对此的回应。

If you want to pass the argument to be converted as a shell script parameter, encase the parameter in "'s.

如果要将要转换的参数作为 shell 脚本参数传递,请将参数括在 "'s.

#!/bin/bash
x=$(printf '%q' "")
echo $x

I really like the printf solution, since it does every special character, just like bash.

我真的很喜欢 printf 解决方案,因为它可以处理每个特殊字符,就像 bash 一样。

回答by panticz

The solution from "sehe" works fine, in addition, you can also use double quotes (") instead of single apostrophe (') to by able to use variables:

"sehe" 的解决方案工作正常,此外,您还可以使用双引号 (") 代替单撇号 (') 来使用变量:

x="a real \good %* load of crap from ${USER}"
echo $(printf '%q' "$x")

Of course the string may not contain $ or " itself or you have to escape those manulally by splash \$.

当然,字符串可能不包含 $ 或 " 本身,或者您必须通过启动 \$ 手动转义这些。

回答by Shen Wei

ls  --quoting-style=escape /somedir

this will output the escaped filenames, and also work with unicode characters, printf method does not work with Chinese, it outputs something like $'\206\305...'

这将输出转义的文件名,也适用于 unicode 字符,printf 方法不适用于中文,它输出类似 $'\206\305...' 的内容