Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how i can comment (#) 6 lines before and after the matched pattern in sed

Tags:

regex

vim

sed

perl

I want to comment(#) 6 lines before and after the matched pattern. I referred this question.

How do I delete a matching line, the line above and the one below it, using sed?

I tried to use hold buffer for this solution, but not working.

I have the following sequence occurring multiple times in a file:

aaaa  
bbbb  
cccc  
dddd  
eeee  
ffff  
gggg  
hhhh  
iiii  
jjjj  
kkkk  
llll  
mmmm  
nnnn  
oooo  

If I searched hhhh, then the output file should be given below:

  aaaa  
  #bbbb  
  #cccc  
  #dddd  
  #eeee  
  #ffff  
  #gggg  
  #hhhh  
  #iiii  
  #jjjj  
  #kkkk  
  #llll  
  #mmmm  
  #nnnn  
  oooo  

Please help me to do this with sed or any other scripts!!!

like image 953
joshy Avatar asked Nov 19 '25 18:11

joshy


1 Answers

The question is tagged Vim, so… my beloved :help :global and :help :normal to the rescue!

:g/hhhh/-6,+6norm I#

:substitute variant:

:g/hhhh/-6,+6s/^/#

Breakdown:

  • The :global command is used to execute an Ex command for each line matching the given pattern.

    :g/hhhh/d would delete every line containing hhhh.

  • Ex commands usually accept an optional range. A range can use absolute line numbers, 5,15 and/or relative line numbers, -3,+41.

    :g/hhhh/-6,+6d would delete everything between 6 lines above and 6 lines below every line containing hhhh.

  • The :normal command allows us to execute normal commands from the command-line and it accepts a range, like the other Ex commands. I# is the simplest way to insert a # at the beginning of a line so we can do :normal I# from the command-line, which brings us to the first solution:

    :g/hhhh/-6,+6norm I#
    
  • As an Ex command, :substitute also accepts a range so we can use it as well to insert a # at the beginning of each line in the range, which brings us to the second solution:

    :g/hhhh/-6,+6s/^/#
    
like image 149
romainl Avatar answered Nov 22 '25 07:11

romainl



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!