2016-04-21 47 views
1

我:如何将新行添加到文件和匹配从上一个行缩进

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 

有人可以帮我解决我失踪的问题吗?

+0

的'&'在您的替换字符串被转换为“整个匹配的字符串”。然后你将该字符串的一部分添加到它。那是故意的吗?它似乎不是,根据您的预期输出。 – ghoti

回答

5

您可以捕捉到压痕,然后用替换,将其插入:

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 
/

但有可能与压脚提升a命令一个更优雅的解决方案。

+0

我认为用'a'是不可能改变你插入的东西的,所以你的解决方案是我能想到的唯一的一次性解决方案。 –

+0

@andlrc感谢您的回复,我实际上是通过添加另一行来编辑yaml文件。这里是我根据你的建议使用的: 'sed -i''“s/^ \(* \)name:'$ api_name'$ /&\ n \ 1 \ $ ref:$ 1 /”$ 2' 但我越来越: ' globalweather: 名称:“globalweather:1.0.0'n $ REF:globalweather_1.0.0.yaml ' 我想: ' globalweather: $ REF:globalweather_1.0.0 .yaml ' 我错过了什么? – y17chen

0

@andlrc,感谢您的建议,我知道了它的工作,sed命令我使用的是:

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

相关问题