string 如何在 bash printf 中转义一系列反斜杠?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/31224368/
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-09-08 16:24:42  来源:igfitidea点击:

How do I escape a series of backslashes in a bash printf?

stringbashescapingbackslash

提问by Charney Kaye

The following script yielded an unexpected output:

以下脚本产生了意外的输出:

printf "escaped slash: \ \n"
printf "2 escaped slashes: \\ \n"
printf "3 escaped slashes: \\\ \n"
printf "4 escaped slashes: \\\\ \n"

Run as a bash script under Ubuntu 14, I see:

在 Ubuntu 14 下作为 bash 脚本运行,我看到:

escaped slash: \
2 escaped slashes: \ 
3 escaped slashes: \ 
4 escaped slashes: \

Err.. what?

呃……什么?

采纳答案by Eugeniu Rosca

Assuming that printfFORMATstring is surrounded by double quotes, printftakes one additional level of expansion, compared to e.g. echo(both being shell builtin commands).

假设printfFORMAT字符串被双引号包围printf,与 eg echo(两者都是 shell 内置命令)相比,需要一个额外的扩展级别。

What you expect from printfcan actually be achieved using single quotes:

printf使用单引号实际上可以实现您的期望:

printf '1 escaped slash:   \ \n'
printf '2 escaped slashes: \\ \n'
printf '3 escaped slashes: \\\ \n'
printf '4 escaped slashes: \\\\ \n'

outputs:

输出:

1 escaped slash:   \
2 escaped slashes: \
3 escaped slashes: \\
4 escaped slashes: \\

回答by Cyrus

printfis a bash builtin. Look at help printf:

printf是一个内置的 bash。看看help printf

printf [-v var] format [arguments]
      Formats and prints ARGUMENTS under control of the FORMAT.

You should pass the format and the argument. So add the format "%s\n"before the argument:

您应该传递格式和参数。所以"%s\n"在参数之前添加格式:

printf "%s\n" "escaped slash: \"
printf "%s\n" "2 escaped slashes: \\"
printf "%s\n" "3 escaped slashes: \\\"
printf "%s\n" "4 escaped slashes: \\\\"

Output:

输出:

escaped slash: \ 
2 escaped slashes: \ 
3 escaped slashes: \\ 
4 escaped slashes: \\