如何对现有bash变量进行ANSI C引用? [英] How can I do ANSI C quoting of an existing bash variable?

查看:47
本文介绍了如何对现有bash变量进行ANSI C引用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我查看了这个问题,但没有涵盖我的用例.

I have looked at this question, but it does not cover my use case.

假设我有一个变量 foo ,它包含四个字符的文字 \ x60 .

Suppose I have the variable foo which holds the four-character literal \x60.

我要执行 ANSI C报价在此变量的内容上,并将其存储到另一个变量 bar 中.

I want to perform ANSI C Quoting on the contents of this variable and store it into another variable bar.

我尝试了以下方法,但是都没有达到预期的效果.

I tried the following, but none of them achieved the desired effect.

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

输出:

$foo
\x61

所需的输出( \ x61 的实际值):

Desired output (actual value of \x61):

a

在一般情况下(包括不可打印的字符),我该如何实现?请注意,在这种情况下,仅以 a 作为示例,以便更轻松地测试该方法是否有效.

How might I achieve this in the general case, including non-printable characters? Note that in this case a was used just as an example to make it easier to test whether the method worked.

推荐答案

到目前为止,如果您使用的是 bash :

By far the simplest solution, if you are using bash:

printf %b "$foo"

或者,将其保存到另一个变量名 bar :

Or, to save it in another variable name bar:

printf -v bar %b "$foo"

help printf :

除了printf(1)中描述的标准格式规范外和printf(3),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)

尽管有一些极端情况:

\ c终止输出,不会删除\',\和\?中的反斜杠,并且以\ 0开头的八进制转义字符最多可以包含四个数字

\c terminates output, backslashes in \', \", and \? are not removed, and octal escapes beginning with \0 may contain up to four digits

这篇关于如何对现有bash变量进行ANSI C引用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆