Get a range of lines from a file and replace a line in that range using awk or sed or both

1

I would like to replace a line in a section of the smb.conf file using either awk or sed or both if need be. Here's the section in the file...

[CMI] oplocks = no wide links = no writeable = yes delete readonly = yes path = /LOCALSITE/CMI comment = CMI Data write list = @cbishare valid users = @cbishare create mode = 775 directory mode = 775

I would like to use this code for later reuse with a variable to run on different sections of the smb.conf file. So just finding "write list" in each section will not work.

I am able to parse the file and get the section using this code...

awk '/\[\CMI\>\]/,/^$/' /etc/samba/smb.conf

or with sed...

sed -n '/\[\CMI\>\]/,/^$/{p}' /etc/samba/smb.conf

I now need to replace in the file a specific line in that range like 'write list'. I am a novice with sed or awk and I haven't found any info on how to accomplish the last part.

I thought maybe i could get the NR of the line and then use sed to rewrite it.

Any thoughts on how to do this or links to a solution would be greatly appreciated.

Matt Pedigo

Posted 2014-10-02T17:58:49.073

Reputation: 13

Answers

0

With sed

To replace the value of "write list" in the CMI section and only the CMI section:

sed '/\[\CMI\>\]/,/^$/ s/\s*write list =.*/ write list = New Value/' smb.conf

This replaces the old value of write list with New Value. It assumes, as was assumed in your code, that the sections in smb.conf end with a blank line.

With awk

Similarly:

awk '/\[\CMI\>\]/,/^$/ {if ($1=="write" && $2=="list") {$0=" write list = New Value"}} 1' smb.conf

John1024

Posted 2014-10-02T17:58:49.073

Reputation: 13 893

Thanks John. I choose sed version and it worked after a minor change of removing the first "*" in the search expression before "write". – Matt Pedigo – 2014-10-02T20:02:17.837

Actually I didn't need to remove the first "". It works either way. I also edited the command for inline editing of the file with the -i flag so i looks like this... 'sed -i '/[\CMI>]/,/^$/ s/\swrite list =.*/ write list = New Value/' smb.conf' – Matt Pedigo – 2014-10-02T20:19:06.423

@MattPedigo Very good. – John1024 – 2014-10-02T20:38:16.033

Reworked it to this...'sed -i '/[\CMI>]/,/^$/ s/\swrite list =./&,new value/' smb.conf' – Matt Pedigo – 2014-10-02T20:42:20.307