Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

Consider a text file users.txt:


I need to comment everything from (exclusive) the last commented line until (inclusive) dotan. This is the result:


Is there a nice sed oneliner to do this? I'll be happy with any tool, not just sed, really.

Currently I am getting the line number of the last commented line as so:

$ cat -n users.txt | grep '#' | tail -n1
  2 #bob

I then add one and comment with sed:

$ sed -i'' '3,/dotan/ s/^/#/' users.txt

I know that I could be clever and put this all together with some bc into an ugly one-liner. Surely there must be a cleaner way?

share|improve this question

2 Answers 2

up vote 3 down vote accepted

How about

perl -pe '$a=1 if s/^dotan/#$&/; s/^[^#]/#$&/ unless $a==1;' file

or, the same idea in awk:

awk '(/^dotan/){a=1; sub(/^/,"#",$1)} (a!=1 && $1!~/^#/){sub(/^/,"#",$1);}1; ' file
share|improve this answer
Perfect, thank you! –  dotancohen Jul 21 '14 at 13:36

If the existing commented lines form a single contiguous block, then you could match from the first commented line instead, commenting-out only those lines up to and including your end pattern that are not already commented

sed '/^#/,/dotan/ s/^[^#]/#&/' file

If the existing comments are not contiguous, then due to the greedy nature of the sed range match I think you would need to do something like

tac file | sed '/dotan/,/^#/ s/^[^#]/#&/' | tac

i.e. match upwards from the end pattern to the 'first' comment - obviously that's not so convenient if you want an in-place solution though.

share|improve this answer
Thank you, I've learned from this. –  dotancohen Jul 21 '14 at 20:51

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.