How to Toggle Flag/Switch Value with Sed

I am trying to figure out a one liner to toggle a flag variable. eg.

FLAG=0

Is there a way to use sed to toggle above example between 0 and 1. That is if run with flag set to zero it would change it to one if run again it would set it to zero.

I thought I had it figured but the expressions would end up switching it 2x.

Thank you,
Brian

I would suggest you use awk instead

$ awk 'BEGIN{f=!f;print f;f=!f;print f}'
1
0

There's probably a few ways to do this and I'm pretty sure this is not the easiest-

/^flag/ {
  /1$/ {
    s/flag=1/flag=0/
    b
  }
  /0$/ {
    s/flag=0/flag=1/
  }
}

But run w/ this-

> sed -f flg-script

You can put in flag=0, hit enter and it will return flag=1. And vice-versa
Or run flag=0 in flag.txt as such-

> sed -f flg-script < flag.txt

Good luck.

---------- Post updated at 12:47 AM ---------- Previous update was at 12:33 AM ----------

Oh just wait!
Here's a one liner and neat and clean-

/flag/ y/01/10/

w00t.

1 Like

@fiendracer, I had done this before, but could not remember/find it. Thanks

Glad to have been able to be of service.

well, if you want to toggle the string FLAG=0

$ awk -F"=" '/FLAG/{$2=!$2;print}' OFS="=" file

@ghostdog, I was really looking for that specific sed one liner. I was pulling out my hair trying to remember. Thanks for helping.