分页: 1 / 1

printf中的多次转义

发表于 : 2017-04-11 23:41
whaha
这个容易理解。

debian8@debian:~$ printf "%-5s\n" "hah"
hah

这个呢? \\n --> \n
debian8@debian:~$ printf "%-5s\\n" "hah"
hah

按照上面的逻辑 \\\n如何解析? \\\n -->\\n --> \n 为何输出 \n(字面),咩有换行?

debian8@debian:~$ printf "%-5s\\\n" "hah"
hah \ndebian8@debian:~$

下面几个,我就菜了。

debian8@debian:~$ printf "%-5s\\\\n" "hah"
hah \ndebian8@debian:~$ printf "%-5s\\\\\n" "hah"
hah \
debian8@debian:~$ printf "%-5s\\\\\\n" "hah"
hah \


请解释一下,bash的这种行为?

Re: printf中的多次转义

发表于 : 2017-04-12 2:53
科学之子
这里不仅printf命令有转义,还要处理shell的转义
printf "\\"其实传给printf的只有一个"\"
printf "\\\\"传给printf的就是两个"\"即"\\"
因为命令参数里如果有'\'的话,在shell里就需要转义,而传给命令的参数是转义之后的结果

Re: printf中的多次转义

发表于 : 2017-04-12 7:15
whaha
<table>
<tr>
<td></td>
<td>\n</td>
<td>\\n</td>
<td>\\\n</td>
<td>\\\\n</td>
<td>\\\\\n</td>
<td>\\\\\\n</td>
<td>\\\\\\\n</td>
</tr>
<tr>
<td>escaping by "</td>
<td>none</td>
<td>\n</td>
<td>\\n</td>
<td>\\n</td>
<td>\\\n</td>
<td>\\\n</td>
<td>\\\\n</td>
</tr>
<tr>
<td>escaping by printf</td>
<td>newline</td>
<td>newline</td>
<td>\n literally</td>
<td>\n literally</td>
<td>\+newline</td>
<td>\+newline</td>
<td>\\n literally</td>
</tr>
</table>

Re: printf中的多次转义

发表于 : 2017-04-12 8:23
科学之子
仔细试了试,虽然我2楼原理说的没问题
但实测发现\n其实并不是转义后传递给程序,而是原样传递给程序,不知为何
viewtopic.php?f=21&t=483475&p=3188783#p3188783
楼主可以试试 echo "xxx"这样输出的就是转义后传递给程序的真实参数

Re: printf中的多次转义

发表于 : 2017-04-12 8:54
科学之子
@whaha
我的问题找到了答案,同时又再次复习man bash
Words of the form $'string' are treated specially. The word expands to string, with backslash-escaped characters replaced as specified by the ANSI C standard.
用$'xxx'这样的形式转义应该就可以达到您的要求了
PS:
以前从来没用过这种格式就完全忽略了这种用法,原来这才是全能的escape用法