开发者

escaped filename slashes

I want to generate filename from a user-inputed string and 开发者_运维问答to make sure that it is safely escaped.

for example, if the user enters /usr/bash the output will be \/usr\/bash and if the input is The great theater the output is The\ great\ theater.


Are you sure you need to do this? This is kind of a code smell. There's very likely a better way to do whatever you're trying to do than mangling your input. Properly quoting your variables when you use them usually suffices:

$ file='some file name.txt'
$ touch "$file"
$ ls "$file"
some file name.txt

If you insist, though, use the %q format with printf:

$ str='The great theater'
$ printf '%q\n' "$str"
The\ great\ theater
$ escaped=$(printf '%q' "$str")
$ echo "$escaped"
The\ great\ theater

Note that this won't escape slashes as they aren't normally special characters.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜