Sed: would like to return an error for empty string

There are actually two things that I want to do:

  1. Detect if there is a 3 digit number and if so return an error (working)
  2. Detect if there is an empty string and return an error if so (not working)

I would like to do 1 & 2 using the sed command only once; I'm trying to do things correctly and efficiently.

I have so far:

echo "" | sed -n -r '/[0-9]{3}/{q100}; //{q100}'; echo $?

(For newbies: -n quiets text output, -r allows for GNU program to do true regex, {q100} returns error '100', '$?' is the last returned result)

The result is 0, which is not what I want as the string is empty. My attempt is the portion '//{q100}', but I can see that it is difficult to test against nothing-quite perplexing actually.

Try testing for "start-of-line nothing end-of-line":

echo "" | sed -n -r '/[0-9]{3}/{q100}; /^$/{q200}'; echo $?
200

And, wouldn't it make sense to have different codes for different errors?

3 Likes

Indeed. I've just added them. :o

Such a simple solution. Thanks so much.