2017-01-23 48 views
0

我有一個包含以下內容的測試文件。bash腳本在逗號後附加數據

[groups] 

test_read = apple,orange 
write = grapes,mango 
[TEST:/] 
@test_read= apple,orange 
@write= grapes,mango 

我需要添加對所有下組部分中的字段的字覆盆子其是上述[TEST:/]

預期輸出

[groups] 

    test_read = apple,orange,raspberry 
    write = grapes,mango,raspberry 
    [TEST:/] 
    @test_read= apple,orange 
    @write= grapes,mango 

我與這一個襯墊試圖

awk 'NF > 1 {$NF = $NF ",raspberry"} 1' test 

但它是在所有的領域添加覆盆子。

+0

爲什麼是預期的輸出? 'tabbed'? – Inian

回答

0
awk '/\[groups/{a=1;print;next} /^\[/{a=0}a && /=/{$0=$0",raspberry"}7' file 

無論位於何處groups塊,該生產線都可以正常工作。 (例如在TEST塊之上或之下)。

+0

工作就像一個魅力謝謝。你能告訴我它是如何工作的嗎? – catchvenki

+0

@catchvenki它搜索'[groups',如果找到了,我讓awk知道下面的行,直到下一個'[..]'或EOF,我們應該將字符串追加到包含'='的所有行。當下一個'[..]'來臨時,我們停止附加邏輯。 – Kent

+0

HI肯特,我可以知道如何將此輸出重定向到文件。現在它只能打印正確的輸出。但當我打開文件更新的數據不存在 – catchvenki

0

您可以使用此命令sed

sed '1,/\[TEST:\/\]/{/=/s/$/,raspberry/;}' file 

[groups] 

test_read = apple,orange,raspberry 
write = grapes,mango,raspberry 
[TEST:/] 
@test_read= apple,orange 
@write= grapes,mango 

要保存更改內嵌使用:

sed -i.bak '1,/^[ \t]*\[TEST:\/\]/{/=/s/$/,raspberry/;}' file 

工作原理:

1,/^[ \t]*\[TEST:\/\]/ # search between 1st line and the line where [TEST:/] is found 
{ 
    /=/     # only act on line where = is found (fields) 
    s/$/,raspberry/;  # replace end of line with ,raspberry 
} 
0

可以在gawk

awk 'f && /=/{$0=$0 ",raspberry"} 
    match($0, /^\[([^\]]*)\]$/, a){f=(a[1]=="groups")}1' file 

你使用match

[groups] 

test_read = apple,orange,raspberry 
write = grapes,mango,raspberry 
[TEST:/] 
@test_read= apple,orange 
@write= grapes,mango 
1
$ awk '/\[/{f=/groups/} f{if (NF) $0=$0",raspberry"} 1' file 
[groups],raspberry 

test_read = apple,orange,raspberry 
write = grapes,mango,raspberry 
[TEST:/] 
@test_read= apple,orange 
@write= grapes,mango