【问题标题】:How to add a new line to a file and match the indentation from prev line如何在文件中添加新行并匹配上一行的缩进
【发布时间】:2016-04-21 23:04:09
【问题描述】:

我有:

globalweather:
    name: 'globalweather:1.0.0'

我试过了: sed -i '' "s/^\( *\)name: '$api_name'$/&\n\1\$ref: $1/" $2

但我得到了:

globalweather:
    name: 'globalweather:1.0.0'n    $ref: globalweather_1.0.0.yaml 

我想要:

globalweather:
   $ref: globalweather_1.0.0.yaml 

有人可以帮我解决我所缺少的吗?

【问题讨论】:

  • 替换字符串中的& 被转换为“整个匹配的字符串”。然后你要向它添加部分字符串。这是故意的吗?根据您的预期输出,它似乎不是。

标签: shell sed scripting


【解决方案1】:

您可以捕获缩进,然后使用替换来插入它:

sed 's/^\( *\)something$/&\n\1something else/'

细分:

s/
  ^      # Start of string
  \( *\) # Capture 0 or more spaces
  something
  $      # End of string
/
  &      # Full matched string
  \1     # Captured spaces
  something else
/

after 命令可能会提供更优雅的解决方案。

【讨论】:

  • 我认为a 无法更改您插入的内容,因此您的解决方案是我能想到的唯一一次性解决方案。
  • @andlrc 感谢您的回复,我实际上正在尝试通过添加另一行来编辑 yaml 文件。这是我根据您的建议使用的:sed -i '' "s/^\( *\)name: '$api_name'$/&\n\1\$ref: $1/" $2 但我得到:` globalweather:name:'globalweather:1.0.0'n $ref:globalweather_1.0.0.yaml `我想要:` globalweather:$ref: globalweather_1.0.0.yaml `我错过了什么?
【解决方案2】:

@andlrc,谢谢你的建议,我搞定了,我使用的 sed 命令是:

sed -i '' "s/^\( *\)name: '$api_name'$/\1\$ref: $1/" $2

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-01-30
    • 1970-01-01
    • 2011-04-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多