我有一个包含以下内容的测试文件。
[groups]
test_read = apple,orange
write = grapes,mango
[TEST:/]
@test_read= apple,orange
@write= grapes,mango
我需要在[TEST:/]
之上的分组部分下的所有字段中添加单词raspberry预期输出
[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 :(得分: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
答案 1 :(得分: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
}
答案 2 :(得分:0)
awk '/\[groups/{a=1;print;next} /^\[/{a=0}a && /=/{$0=$0",raspberry"}7' file
无论groups
块位于何处,此行都可以使用。 (例如,在TEST
区块之上或之下)。
答案 3 :(得分:0)
您可以在match
gawk
awk 'f && /=/{$0=$0 ",raspberry"}
match($0, /^\[([^\]]*)\]$/, a){f=(a[1]=="groups")}1' file
你明白了,
[groups]
test_read = apple,orange,raspberry
write = grapes,mango,raspberry
[TEST:/]
@test_read= apple,orange
@write= grapes,mango