Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

grep returns no matches for following expression

Using the (?<=_)(.*)(?=\.) regex with the 23353_test.txt test string returns nothing with grep with the -p option. It doesn’t show errors either. I expect the return to be test. But when the regex is tried in regex101.com it runs correctly.

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

The following GNU grep command extracts the right substring:

grep -oP '(?<=_).*(?=\.)' file

Note that .* matches greedily, and if you want to make sure you match a substring between the closest _ and . you need to use a

grep -oP '(?<=_)[^._]*(?=\.)' file

where [^._]* matches zero or more chars other than . and _.

If you cannot rely on your grep, you can use sed here:

sed -n 's/.*_\(.*\)\..*/\1/p' file

See the online demo:

#!/bin/bash
s='23353_test.txt'
grep -oP '(?<=_)(.*)(?=\.)' <<< "$s"
# => test
sed -n 's/.*_\(.*\)\..*/\1/p' <<< "$s"
# => test
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading