3

I have the below lines in a file:

SUT_INST_PIT=true
SUT_INST_TICS=true
SUT_INST_EXAMPLES=false
SUT_INST_PING=false

How can i create a sed line to match pattern SUT_INST_EXAMPLES & SUT_INST_PING and set false to true?

I can't simply replace false with true because I don't want to change SUT_INST_PIT & SUT_INST_TICS even if they are false!!!

I have at the moment two sed commands that are working, but i would like one line only!

sed -i "s/SUT_INST_EXAMPLES=false/SUT_INST_EXAMPLES=true/g" <file>
sed -i "s/SUT_INST_PING=false/SUT_INST_PING=true/g" <file>

One more thing the sed line should be able to be parametrized to set false->true or true->false, but only for SUT_INST_EXAMPLES & SUT_INST_PING.

Solution (according to @RomanPerekhrest) and how to use it in send (expect script):

send "sed -i 's\/^\\(SUT_INST_EXAMPLES\\|SUT_INST_PING\\)=false\/\\1=true\/' file\r"
2

sed approach:

sed -i 's/^\(SUT_INST_EXAMPLES\|SUT_INST_PING\)=false/\1=true/' file

file contents:

SUT_INST_PIT=true
SUT_INST_TICS=true
SUT_INST_EXAMPLES=true
SUT_INST_PING=true

\(SUT_INST_EXAMPLES\|SUT_INST_PING\) - alternation group, matches either SUT_INST_EXAMPLES OR SUT_INST_PING at the start of the string


Alternative gawk(GNU awk) approach:

gawk -i inplace -F'=' -v OFS='=' '$1~/^SUT_INST_(EXAMPLES|PING)/{$2=($2=="false")? "true":"false"}1' file
  • I am trying to use the sed line from your answer in a expect send command but it is failing: SUT:/home # =true/' file -i 's/^(SUT_INST_EXAMPLES|SUT_INST_PING)=false/ -bash: syntax error near unexpected token SUT_INST_EXAMPLES – FotisK May 9 '17 at 21:04
  • Updated Question with solution according to @RomanPerekhrest. – FotisK May 10 '17 at 18:06
2

You can simply toggle with:

sed -i -E '/^SUT_INST_(PING|EXAMPLES)=/{s/false/true/;t;s/true/false/;}' infile

This will change true to false or false to true depending on the current value.

0

sed allows you to do multiple operations on each line:

sed -e '...' -e '...' file

So you can at least combine your two sed invocations into one with

sed -i -e 's/^SUT_INST_EXAMPLES=false/SUT_INST_EXAMPLES=true/' \
       -e 's/^SUT_INST_PING=false/SUT_INST_PING=true/' file

To parametrize the replacement, use variables:

examples="true"
ping="false"

sed -i -e "s/^SUT_INST_EXAMPLES=.*\$/SUT_INST_EXAMPLES=$examples/" \
       -e "s/^SUT_INST_PING=.*\$/SUT_INST_PING=$ping/" file

The above will unconditionally set the values of SUT_INST_EXAMPLES and SUT_INST_EXAMPLES to that of $examples and $ping respectively.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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