2016-04-21 50 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

相關問題