--In many cases, you use a Mac to grep for work or hobbies to search or aggregate. --At that time, you may encounter the error as the title. ――Therefore, this time, I will record two points to be taken when this error occurs.
--There are the following two methods. ** * If you are in a hurry, we recommend installing the GNU version. ** **
--Introduce the GNU version of grep with brew install grep
.
-** * Mac standard grep is BSD version. ** **
--Modify the way to write grep so that it works on BSD.
-** * Detailed contents are explained in the following Contents orchids. ** **
--The error occurs in the following example.
#Search for Hello or World or empty in the string.
echo -e "Hello\nWorld" | grep -E '(Hello|World|)'
#Error output
grep: empty (sub)expression
--The following are possible causes. -** A regular expression search adds an empty space to the candidates. ** ** -** I've heard that the GNU and BSD versions have different detailed behaviors. ** ** --For verification, when I verified it in the GNU grep environment prepared by Docker, there was no problem with the above writing method. ――From this, it was found that the cause was a small difference in behavior in the processing when empty was selected.
--To identify the cause, solve it by the following two methods.
--Install the GNU version of grep.
--Modify to write grep so that it works on BSD
--The first GNU version is completed by simply passing the following command.
- brew install grep
――The second is to change the processing when empty is selected as follows.
#Recognize with symbols at the beginning and end of the line.
echo -e "Hello\World" | grep -E '(^|Hello|World)'
#Deleted the empty selection process itself.
echo -e "Hello\nWorld" | grep -E '(Hello|World)'
-** * There are advantages and disadvantages to both methods, so select the safe one **
--From the above, we recognize the small differences in behavior depending on each OS / library. ――Therefore, be aware of highly portable descriptions.