如何转义字符串中的特殊字符?

hua*_*n68 20 bash

假设$file持有一个文件名的值,比如Dr' A.tif. 在 bash 编程中,如何在$file不删除特殊字符的情况下转义单引号和任何其他特殊字符?

2014 年 7 月 9 日更新

根据@Gilles 的请求,以下代码片段无法处理Dr' A.tif

files=$(find /path/ -maxdepth 1 -name "*.[Pp][Dd][Ff]" -o -name "*.[Tt][Ii][Ff]")
echo "${files}" > ${TEMP_FILE}
while read file
do
   newfile=$(echo "${file}" | sed 's, ,\\ ,g') ## line 1
done < ${TEMP_FILE}
Run Code Online (Sandbox Code Playgroud)

在我尝试了@Patrick on的答案后line 1,它似乎对我有用。但是,如果我有诸如Dr\^s A.tif,printf命令之类的文件,它似乎没有帮助,它会向我显示Dr\^s\ A.tif. 如果我像这样在控制台上手动尝试:

printf "%q" "Dr\^s A.tif"

我会有这个输出:

Dr\\\^s\ A.tif

知道如何处理吗?

phe*_*mer 22

您可以使用printf内置 with%q来完成此操作。例如:

$ file="Dr' A.tif"
$ printf '%q\n' "$file"
Dr\'\ A.tif

$ file=' foo$bar\baz`'
$ printf '%q\n' "$file"
\ foo\$bar\\baz\`
Run Code Online (Sandbox Code Playgroud)

从 bash 文档中printf

In addition to the standard format specifications described in printf(1)
and printf(3), printf interprets:

 %b       expand backslash escape sequences in the corresponding argument
 %q       quote the argument in a way that can be reused as shell input
 %(fmt)T  output the date-time string resulting from using FMT as a format
          string for strftime(3)
Run Code Online (Sandbox Code Playgroud)


gar*_*Red 4

尝试:-

file=Dr\'\ A.tif
echo $file
Dr' A.tif
Run Code Online (Sandbox Code Playgroud)

或者

file="Dr' A.tif"
echo $file
Dr' A.tif
Run Code Online (Sandbox Code Playgroud)

或者如果字符串包含双引号:-

file='Dr" A.tif'
echo $file
Dr" A.tif
Run Code Online (Sandbox Code Playgroud)

网上有关于转义和引用的很好的教程。从这个开始吧。


归档时间:

查看次数:

140267 次

最近记录:

8 年,8 月 前