Sed or awk to replace a line in a block

2019-03-07 05:17发布

Input file contains:

[abc]  
para1=123  
para2=456  
para3=111  

[pqr]  
para1=333  
para2=765  
para3=1345  

[xyz]  
para1=888  
para2=236  
para3=964  

Requirement of shell script is to replace the one parameter of particular block
Ex: Replace para2=765 with para2=999 of block [pqr]
Please help me how can I achieve this with sed or awk command.

标签: bash shell awk sed
4条回答
成全新的幸福
2楼-- · 2019-03-07 05:18

This might work for you (GNU sed):

sed '/\[pqr\]/,/^\s*$/s/\(para2=\)[0-9]*/\1999/' file

Substitute the number following para2= within the block starting [pqr] to an empty line.

查看更多
放我归山
3楼-- · 2019-03-07 05:33

THE idiomatic awk solution is:

$ awk 'BEGIN{RS=""; ORS="\n\n"; FS=OFS="\n"} $1=="[pqr]"{$3="para2=999"} 1' file
[abc]
para1=123
para2=456
para3=111

[pqr]
para1=333
para2=999
para3=1345

[xyz]
para1=888
para2=236
para3=964
查看更多
姐就是有狂的资本
4楼-- · 2019-03-07 05:34

Through sed another way,

$ sed -r ':l /^\[pqr\]/{:loop ;n;/^$/{b l};s/(para2=).*/\1999/g;b loop;}' file_name

b loop   - Using the looping concept getting the line one by one.
^\[pqr\] - If the corresponding pattern is found.
^$       - Represent new line only.
s/       - Replacement to particular pattern.
n        - For getting next line
查看更多
Explosion°爆炸
5楼-- · 2019-03-07 05:39

Here is how I would do it:

awk '/^\[pqr\]/ {sub(/^para2=.*/,"para2=999")}1' RS= ORS="\n\n" file
[abc]
para1=123
para2=456
para3=111

[pqr]
para1=333
para2=999
para3=1345

[xyz]
para1=888
para2=236
para3=964

By setting RS to nothing, you make awk work in block mode separated by blank lines.
Then make sure we are in correct block by search for block starting with [pqr]
In this block, change the data from para2=765 to para2=999, then print it.


Another way to do it:

awk '/^\[pqr\]/ {f=1} f && sub(/^para2=.*/,"para2=999"){f=0}1' file

Set a flag if pqr is found, change the data if flag is true, reset the flag.

查看更多
登录 后发表回答