Awk command to add and delete lines from a block

2019-09-19 18:53发布

问题:

my input file has blocks like

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

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

[xyz]    
para1=888    
para2=236    

I have two requirements:

  1. Add a line to a block, ex: add ‍‍‍‍‍‍‍para4=uiy to block [pqr]
  2. To delete a parameter from a block, ex: delete para2=236 from block [xyz]

Please help me how can I achieve this with awk command

回答1:

Add a param

awk -F"\n" '$1~/pqr/{$(NF+1)="para4=uiy"}1' OFS="\n" RS= file

If it always adds the last one and you dont know the number you could use

awk -F"\n" '$1~/pqr/{$(NF+1)="para"NF"=uiy"}1' OFS="\n" RS=

Remove a param

awk -F"\n" '$1~/xyz/{gsub(/\npara2=236/,"")}1' OFS="\n" RS= file


回答2:

Here is another solution. By setting RS to nothing, awk works with blocks. (OSCam?)

awk '/^\[pqr/ {$0=$0"\npara4=uiy"} /^\[xyz/ {sub(/para2=[0-9]*/,"")}1' RS= ORS="\n\n" file
[abc]
para1=123
para2=456
para3=111
para4=666

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

[xyz]
para1=888


标签: shell awk