Escape filenames the same way Bash does it

后端 未结 6 1390
攒了一身酷
攒了一身酷 2020-11-30 06:14

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, a

相关标签:
6条回答
  • 2020-11-30 06:17
    $ 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
    
    0 讨论(0)
  • 2020-11-30 06:19

    I may be a little late to the party but what worked for me is:

    ls  --quoting-style=shell-escape
    

    This way it also escapes characters like ! or '.

    0 讨论(0)
  • 2020-11-30 06:33

    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
    
    0 讨论(0)
  • 2020-11-30 06:33

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

    0 讨论(0)
  • 2020-11-30 06:35

    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.

    0 讨论(0)
  • 2020-11-30 06:43
    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...'

    0 讨论(0)
提交回复
热议问题