Comment all lines from last commented line to line with ‘foo’

sedtext processing

Consider a text file users.txt:

#alice
#bob
charlie
dotan
eric

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

#alice
#bob
#charlie
#dotan
eric

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?

Best Answer

How about

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

or, the same idea in awk:

awk '(/^dotan/){a=1; sub(/^/,"#",$1)} (a!=1 && $1!~/^#/){sub(/^/,"#",$1);}1; ' file