How can I make this Perl one-liner to switch a character on a line in a file?

I am trying to write a one-line Perl script that will switch the line in a config file from "commented" to none and back again. I have the following:

perl -pi -e 's/^(#?)(\tDefaultServerLayout)/ ... /e' xorg.conf

      

I'm trying to figure out what code to put in the replacement section (...). I would like the replacement to insert '#' if it was not matched and remove it if it was matched.

pseudocode:

if ( $1 == '#' ) then
   print $2
else
   print "#$2"

      

My Perl is very rusty and I don't know how to do it in replacement s///e

.

My reason for this is to create a single script that will change (toggle) my display settings between the two layouts. I would prefer it to be done in just one script.

I'm open to suggestions for alternative methods, but I would like to leave this as a one-liner that I can just include in a shell script that does other things I want to do when I change layouts.

0


source to share


1 answer


perl -pi -e 's/^(#?)(?=\tDefaultServerLayout)/ ! $1 && "#" /e' foo

      

Pay attention to the addition? = to simplify the string being replaced using a forward-looking statement .



Some might prefer s /.../$ 1? ":" # "/ e.

+12


source







All Articles