Hi I'm trying to parse through a folder structure and just have the first two folders in a directory passed to a variable. Right now I'm using the regex '/.?/.?/' which works fine except my version of ash on OpenWRT doesn't support Perl and thus the "? are ignored. How can I fix this?
var2=$(echo "$TR_TORRENT_DIR" | grep -Eio '\/.*?\/.*?\/')
echo $var2
Make your regex more specific.
In general, use of non-greedy modifiers is a red flag. It should make you think about whether you can rewrite your regex in a more specific way (so it doesn't matter whether a quantifier is greedy or not).
In this case the problem is .*
(another flag), which matches far too much.
If you use [^/]
instead of .
, you avoid all problems:
/[^/]*/[^/]*/
will match the first two components and nothing more. (Also, there's no need to escape /
; it's not special in a regex.)