简体   繁体   中英

bash regex patch match

I have a path such as thus ..

/Users/me/bla/dev/trunk/source/java/com/mecorp/sub/misc/filename.java

I'd like to be able to use bash to create the package structure in another dir somewhere eg

com/mecorp/sub/misc/

I tried the following but it wont work .. I was able to get a match if I change my regex to .* so that implies my bash is ok - There must be something wrong with the way im quoting the regex or maybe the regex its self. I do see working here ..

http://regexr.com?3439m

So im confused ?

regex="(?<=/java)(.*)(?=/)"


 [[ $fullfile =~ $regex ]]
 echo "pkg name " ${BASH_REMATCH[0]}

Thanks for your time.

EDIT - I'm using OSX so it doesn't have all those nice spiffy GNU extensions.

Try this :

using GNU :

$ echo '/Users/me/bla/dev/trunk/source/java/com/mecorp/sub/misc/filename.java' | 
    grep -oP 'java/\K.*/'
com/mecorp/sub/misc/

See http://regexr.com?3439p

Or using :

x="/Users/me/bla/dev/trunk/source/java/com/mecorp/sub/misc/filename.java"
[[ $x =~ java/(.*/) ]] && echo ${BASH_REMATCH[1]}

Or with :

echo "$x" | awk -F/ '{print gensub(".*/java/(.*/).*", "\\1", $0)}'

Or with :

echo "$x" | sed -e 's@.*/java/\(.*/\).*@\1@'

If you try to extract the path after /java/ you can do it with this:

path=/Users/me/bla/dev/trunk/source/java/com/mecorp/sub/misc/filename.java
package=`echo $path | sed -r 's,^.*/java/(.*/).*$,\1,'`

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM