Escape filenames the same way Bash does it

2019-01-09 01:27发布

问题:

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

For Instance:

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

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

回答1:

Use 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


回答2:

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

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

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

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



回答3:

$ 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


回答4:

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

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 \$.



回答5:

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...'