【问题标题】:How do I remove newline in yaml如何在 yaml 中删除换行符
【发布时间】:2021-03-10 09:53:19
【问题描述】:

我有一个这样的 yaml 文件:

yaml: >-
    random
another: normaltext

在 bash 的帮助下,我想得到这个输出:

yaml: random
another: normaltext

这段文字每次都不一样。

我已经尝试过tr -d '>-',但换行符仍然存在。如果我尝试tr -d '\n',那么整个结构就会崩溃。

【问题讨论】:

  • 您是否可以访问awksed?祝你好运。

标签: bash awk sed git-bash


【解决方案1】:
sed -Ezi 's/>-[[:space:]]+//g' yamlfile

将文件当作一行 (-z) 使用,然后用正则表达式空格、 >- 、一个或多个空格代替。

【讨论】:

  • -z 比使用那些晦涩难懂的模式运算符要容易得多。感谢您的提示。
  • 我会明确匹配\n。请注意,blabla: "some >- value" 也会被修改。喜欢>-[[:blank:]]*\n[[:blank:]]+
【解决方案2】:

一些带有额外(无意义)内容的示例数据:

$ cat yaml.file
yaml: >-
    random
another: normaltext
leave this line ... as is
something else >-
  more stuff on this line
and leave this line alone, too

一个awk解决方案:

$ awk '
/>-/ { sub(">-","")            # if line contains the string ">-" then remove it
       l1=$0                   # save current/modified line in variable "l1"
       getline                 # get next line
       $1=$1                   # strip off leading spaces
       print l1 $0             # print our 2 lines
       next                    # skip to next line
      }
1                              # always true => print the current line
' yaml.file

作为单线无 cmets:

$ awk '/>-/ {sub(">-",""); l1=$0; getline; $1=$1; print l1 $0; next}1' yaml.file

以上生成如下输出:

yaml: random
another: normaltext
leave this line ... as is
something else more stuff on this line
and leave this line alone, too

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-06-20
    • 2017-04-02
    • 1970-01-01
    相关资源
    最近更新 更多