【问题标题】:bash, getting ' characters inside printf statementsbash,在 printf 语句中获取 ' 字符
【发布时间】:2021-04-21 11:13:39
【问题描述】:

我发现很难将 printf 语句嵌套在别名中。我有许多我想提供的帮助主题(只是一些有用的提示,用于在我忘记语法时使用)。我发现printf 需要\ 转义为\\% 转义为%%。但是,我的问题更多是与'"

alias helpx='printf "A note about 'vim'.\n"'
=> A note about vim.   # The ' are ignored.

alias helpx="printf 'A note about 'vim'.\n'"
=> A note about vim.   # The ' are ignored.

alias helpx='printf "A note about \'vim\'.\n"' # Invalid syntax

alias helpx='printf "A note about \"vim\".\n"'
=> A note about "vim".   # Some progress, I can now get " here

如何在上面的笔记中获取' 字符?

【问题讨论】:

  • 这与printf 无关。这是关于嵌套引用。如果将helpx 定义为一个函数会容易得多。
  • 我同意功能会更容易,谢谢。奇怪的是,bash 中的别名和函数如此接近,它们在功能上几乎可以互换,没有太大区别。
  • man bash“关于别名的定义和使用的规则有些混乱。[...] 几乎所有用途,别名都被 shell 函数所取代。”.

标签: bash printf escaping echo


【解决方案1】:

请你试试:

alias helpx='printf "A note about '\''vim'\''.\n"'

或:

alias helpx="printf \"A note about 'vim'.\\n\""

【讨论】:

  • 谢谢,我认为第二种结构最适合我的需要,因为我觉得它总体上是最容易阅读的,但我发现两种方式都可以完美地工作。 ??
【解决方案2】:

在 unix 终端上使用 printf-command 时,您可以执行以下操作来转义字符:

 printf "A note about \'vim\'.\n"

由于您有兴趣将此命令分配给变量(您的别名“helpx”),因此您至少可以通过两种不同的方式执行此操作:

  • 如果您对 ASCI 标点符号和符号有亲和力,那么无需过多处理字符转义,然后使用上述解决方案

    alias helpx='printf "A note about \u0027vim\u0027.\u000A"'
    
  • 如果您对 ASCI 标点符号没有兴趣

    使用@tshiono 提出的答案

希望这在将来处理此类问题时也会有所帮助。

【讨论】:

  • ASCI 标点符号和符号的使用非常有趣,我已经注意到这一点以备将来使用谢谢。
  • @YorSubs,是的,不客气,然后随时更新答案。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-10-31
  • 1970-01-01
  • 2017-03-18
  • 2021-12-27
  • 1970-01-01
  • 2019-04-22
相关资源
最近更新 更多