Reputation: 35
I have a test file with following contents.
[groups]
test_read = apple,orange
write = grapes,mango
[TEST:/]
@test_read= apple,orange
@write= grapes,mango
I need to add the word raspberry on all the fields under groups section which is above [TEST:/]
Expected output
[groups]
test_read = apple,orange,raspberry
write = grapes,mango,raspberry
[TEST:/]
@test_read= apple,orange
@write= grapes,mango
I tried with this one liner
awk 'NF > 1 {$NF = $NF ",raspberry"} 1' test
But it is adding raspberry on all the fields.
Upvotes: 0
Views: 95
Reputation: 203219
$ 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
Upvotes: 1
Reputation: 8164
You can use match
in gawk
awk 'f && /=/{$0=$0 ",raspberry"}
match($0, /^\[([^\]]*)\]$/, a){f=(a[1]=="groups")}1' file
you get,
[groups]
test_read = apple,orange,raspberry
write = grapes,mango,raspberry
[TEST:/]
@test_read= apple,orange
@write= grapes,mango
Upvotes: 0
Reputation: 195039
awk '/\[groups/{a=1;print;next} /^\[/{a=0}a && /=/{$0=$0",raspberry"}7' file
This line works no matter where is the groups
block located. (E.g. is above or under the TEST
block).
Upvotes: 0
Reputation: 784968
You can use this sed
command:
sed '1,/\[TEST:\/\]/{/=/s/$/,raspberry/;}' file
[groups]
test_read = apple,orange,raspberry
write = grapes,mango,raspberry
[TEST:/]
@test_read= apple,orange
@write= grapes,mango
To save the changes inline use:
sed -i.bak '1,/^[ \t]*\[TEST:\/\]/{/=/s/$/,raspberry/;}' file
How it works:
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
}
Upvotes: 0