Issue
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
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
Answered By - Wiktor Stribiżew Answer Checked By - Cary Denson (WPSolving Admin)