簡體   English   中英

如何對現有的bash變量進行ANSI C引用?

[英]How can I do ANSI C quoting of an existing bash variable?

我看過這個問題 ,但它不包括我的用例。

假設我有變量foo ,它包含四個字符的文字\\x60

我想對此變量的內容執行ANSI C Quoting並將其存儲到另一個變量bar

我嘗試了以下,但沒有一個達到預期的效果。

bar=$'$foo'   
echo $bar     
bar=$"$foo"     
echo $bar       

輸出:

$foo
\x61

期望的輸出( \\x61實際值):

a

如何在一般情況下實現此目的,包括不可打印的字符? 請注意,在這種情況下a僅使用a作為示例,以便更容易測試方法是否有效。

到目前為止,最簡單的解決方案,如果你使用bash

printf %b "$foo"

或者,將其保存在另一個變量名稱bar

printf -v bar %b "$foo"

來自help printf

除了printf(1)和printf(3)中描述的標准格式規范外,printf還解釋:

  %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) 

但是有邊緣情況:

\\ c終止輸出,\\',\\“和\\?中的反斜杠不會被刪除,以\\ 0開頭的八進制轉義可能包含最多四位數字

我知道的最好的方法是

  y=$(printf $(echo "$foo"|sed 's/%/%%/g'))

正如評論中所提到的,這會削減$foo尾隨換行符。 要克服這個:

moo=$(echo "${foo}:end"|sed 's/%/%%/g')
moo=$(printf "$moo")
moo=${moo%:end}
# the escaped string is in $moo
echo "+++${moo}---"

我發現我能做到這一點。 根據評論編輯。

bar=$( echo -ne "$foo" )

以下作品:

 eval bar=\$\'$x\'

必須首先構造命令欄= $'\\ x61',然后eval評估新構建的命令。

通過shell轉換的示例。 問題,該代碼是使用八進制\\0nnn使用和hexdecimal(不是在所有殼) \\xnn (其中n是[六]位)

foo="\65"
print "$( echo "$foo" | sed 's/\\/&0/' )"

5

使用awk,你當然可以直接轉換它

從bash 4.4開始,有一個變量擴展可以做到這一點:

$ foo='\x61';     echo "$foo" "${foo@E}"
\x61 a

要設置另一個變量:

$ printf -v bar "${foo@E}";     echo "$bar"
a

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM