为什么bash printf%q会产生不同类型的输出?

时间:2014-02-19 07:47:37

标签: bash shell

我正在编写一个shell脚本,我需要将一个命令的输出作为参数传递给另一个,因此需要正确转义。这似乎是bash printf内置%q格式的教科书用例,所以我们在这里:

在档案test1中,我有以下文字:

  “我不怕你的流行病,男人,”亚哈从舷墙说道,到   站在船尾的梅休船长; “加入进来吧。”但   现在加布里埃尔站起来了。 “想想,想想发烧,黄色   和bilious!小心可怕的瘟疫!“”加布里埃尔!加布里埃尔!“喊道   梅休船长; “你必须要么& mdash;”但那一瞬间一蹴而就   波浪将船射向远方,它的沸腾淹没了所有的言论。   “你见过白鲸吗?”当船漂流时,要求亚哈   背部。 “想一想,想想你的鲸鱼船,沉没和沉没!小心   可怕的尾巴!“

在档案test2中,我有以下文字:

  

但是尽管如此,确实是下属   幽灵很快就在船员中找到了自己的位置,尽管仍然如此   他们在某种程度上与他们截然不同,但头发浑身发达的Fedallah   到最后仍然是一个低沉的谜。

我感到好奇的是printf %q如何对这两个字符串进行不同的转义。

bcollins$ test1=`cat test1`; printf %q "$test1"
$'"I fear not thy epidemic, man," said Ahab from the bulwarks, to\nCaptain Mayhew, who stood in the boat\'s stern; "come on board." But\nnow Gabriel started to his feet. "Think, think of the fevers, yellow\nand bilious! Beware of the horrible plague!" "Gabriel! Gabriel!" cried\nCaptain Mayhew; "thou must either—" But that instant a headlong\nwave shot the boat far ahead, and its seethings drowned all\nspeech. "Hast thou seen the White Whale?" demanded Ahab, when the boat\ndrifted back. "Think, think of thy whale-boat, stoven and sunk! Beware\nof the horrible tail!"'

bcollins$ test2=`cat test2`; printf %q "$test2"
But\ be\ all\ this\ as\ it\ may\,\ certain\ it\ is\ that\ while\ the\ subordinate\ phantoms\ soon\ found\ their\ place\ among\ the\ crew\,\ though\ still\ as\ it\ were\ somehow\ distinct\ from\ them\,\ yet\ that\ hair-turbaned\ Fedallah\ remained\ a\ muffled\ mystery\ to\ the\ last.

在一个中,输出是bash-escaped字符串,未展开。在第二个中,结果完全展开并转义。为什么?我怎样才能保持一致?

1 个答案:

答案 0 :(得分:2)

嗯,这很棘手。

由于第一个文件中存在非ASCII字符而发生这种情况:

either—

printf发现non-ASCII character时,它只是没有将字符串转义为内部并使用

$'<string>'

印刷符号。