Home > front end >  Linux test command with sed is not working
Linux test command with sed is not working

Time:10-18

Here is my code which always returns 'false' only:-

export STR="MYC-14:: This is sample string only."
echo $STR
test -z "$(echo "$STR" |  sed '/^MYC-/p' )" && echo "true" || echo "false" 

I'm trying to match the starting characters "MYC-" from the variable called "STR" but seems like the regular expression within sed condition is wrong due to which test command is returning false.

CodePudding user response:

test -z "$str" succeeds (returns 0) when $str is the empty string. Your sed command is outputting data, so the string is not empty and test is failing (returning non-zero). So the echo "false" branch is executed.

Note that test is not "returning false". It is returning non-zero (eg, it is failing). if does not test boolean conditions, and it is better if you stop thinking about true/false and instead think about success/failure. test failed, because the string it tested was not empty. Because sed generated some output.

If you want to test that a string is not the empty string, use test -n.

CodePudding user response:

By default, sed always outputs the line after processing. Therefore,

echo "$STR" |  sed '/^MYC-/p'

will always output the line: once if it doesn't match, twice if it matches.

Use sed -n to tell sed not to print the line by default.

Most shells make it possible to test this without running an external tool. For example, in bash you can write

if [[ $STR = MYC-* ]] ; then
    ...
fi

CodePudding user response:

Finally, I'm able to make it work:-

export STR="MYC-14:: This is sample string only."
echo $STR

test -z "$(echo "$STR" |  sed '/^MYC-/d' )" && echo "truee" || echo "falsee" 
  • Related