Text Processing – Delete nth Line from a Matched String Using AWK or SED

awksedtext processing

I have a question related to deletion of strings that appear at the n+2 position after the matched string which is at position n using awk for multiple files. I am able to print it using the command:

 awk -F '/radius-server/{nr[NR+4]}; NR in nr' *

Where the matched string is radius-server. Since I'm not too familiar with
awk I would appreciate it if someone could help me delete this line in place , that would mean that I want the files to be modified and saved after the deletion is done.
An example scenario is below –
file 1 which is unmodified

 radius-server dz7HQQH4EqT5 1645-1646
 !
 oj5icqh1dGpSK
 !  
 alias exec t telnet
 alias exec sis show interface status
 !

file 2, after modification is –

radius-server dz7HQQH4EqT5 1645-1646
!
!
alias exec t telnet
alias exec sis show interface status
!

I understand that I can do a pattern matching method using sed -i '/pattern/d' to remove it but that is not what I want as the values change from file to file. Any help would be much appreciated.

Best Answer

sed seems like the right tool:

sed -i '/radius-server/!b;n;n;d' filename

How it works:

/radius-server/!b # as long as it's NOT 'radius-server' do nothing (branch to end)
n # read next line (replace current line with next line)
n # same as above - we now read 2 lines
d # delete the current line

UPDATE - to modify multiple files, simply use glob instead of filename, e.g.

sed -i '/radius-server/!b;n;n;d' *
Related Question