【问题标题】:How can I have a newline in a string in fish shell?如何在鱼壳中的字符串中有换行符?
【发布时间】:2020-05-10 04:44:24
【问题描述】:

是同一个问题 How can I have a newline in a string in sh? 但在鱼壳里。

在 bash 中我们有:

$'this is line\nthis is another line'

谁产生了预期的结果,但在鱼中这不起作用。

fish 有类似的方法吗?

编辑 1:

有 faho 明智地提到的字面方法:

'this is line this is another line'

但我真的很好奇是否存在将\n 的引用作为 shell 中的换行符的方法。

我想知道我是否可以使用此字符串 "this is a line\nthis is another line" 确保鱼将 \n 视为换行符而不是文字。

【问题讨论】:

  • 有趣的是,鱼设计文档describes $'' as "silly"
  • 非常感谢,有趣的是,现在我明白了鱼壳的立场。

标签: string line-breaks fish


【解决方案1】:
  1. Fish 将引号外的 \n 替换为换行符,因此您可以停止并重新开始引号(注意引号前没有“$”):

'这是一行'\n'这是另一行'

  1. Fish 跨行跟随引号,因此您可以包含文字换行符:

'this is line this is another line'

【讨论】:

  • 感谢您花时间回答这个问题。我也可以在 shell 中使用这种方式。有另一种方法可以像在 shell 中一样保持 '\n' 吗?
  • 不,你不能在“shell”中这样做。类似 POSIX 的 shell 不会在 $'' 之外解释 \n - echo 'a'\n'b' 打印 anb。
  • 在fish和POSIX shell中还有echo -e,它将解释字符串中的反斜杠转义,所以echo -e 'a\nb'也将打印a、换行符和b。我建议只使用我给你的第一种方式,因为无论你将参数传递给什么,它都可用。
【解决方案2】:

您可以使用echo -e(启用反斜杠转义的解释),正如@faho 在他的评论中指出的那样:

$ echo -e "## Foo\nBar"
## Foo
Bar

来自man echo:

转义序列

   If -e is used, the following sequences are recognized:

   o \ backslash

   o \a alert (BEL)

   o \b backspace

   o \c produce no further output

   o \e escape

   o \f form feed

   o \n new line

   o \r carriage return

   o \t horizontal tab

   o \v vertical tab

   o \0NNN byte with octal value NNN (1 to 3 digits)

   o \xHH byte with hexadecimal value HH (1 to 2 digits)

【讨论】:

    【解决方案3】:

    编辑您的config.fish 文件。
    Ubuntu 中的示例sudo nano /etc/fish/config.fish
    提示功能是控制鱼终端外观的功能。粘贴此代码:

    # 将系统范围的鱼配置条目放在这里 # 或在 conf.d/ 中的 .fish 文件中 # conf.d 中的文件可以被用户覆盖 # 通过 $XDG_CONFIG_HOME/fish/conf.d 中的同名文件 # 此文件由所有鱼实例运行。 # 要仅包含登录 shell 的配置,请使用 # 如果状态 --is-login # ... # 结尾 # 要仅包含交互式 shell 的配置,请使用 # 如果状态 --is-interactive # ... # 结尾 # function fish_prompt -d "写出提示" # 改变输出颜色 设置 -U fish_color_command '2cff8f' -o # 别名 别名 cls='清除' # 迅速的 printf '%s@%s%s%s%s\n@>' (whoami) (hostname | cut -d . -f 1) \ (set_color $fish_color_cwd) (prompt_pwd) (set_color normal) 结尾

    【讨论】:

      猜你喜欢
      • 2016-03-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-02-24
      • 2011-03-01
      相关资源
      最近更新 更多