I would like to extract the subdirectory name using a bash script from a path like /home/user1/subdir/foo_1/foo_2/.../foo_n.
subdir will always reside under /home/user1 hence the prefix is invariant but there can be varied number of subdirectories under subdir
Some examples:
-
/home/user1/dir1/something/like/this: RESULT: dir1
-
/home/user1/dir2/different/this/time/: RESULT: dir2
- /home/user1/dir3/this/is/the/last/example: RESULT: dir3
I wrote this regex but it doesn’t work correctly:
expr /home/user1/subdir/foo_1/foo_2 : '\/home\/user1\/\(.*\/\)\{1\}'
, but it seems to give subdir/foo_1 instead of subdir.
Thanks!
The problem is that matching is done in a greedy manner.
.*will match as much as it can, which in your case means it will match more than one slash, when you really wanted it to stop at the first slash.You should specifically match everything after
/home/user1/but before the next/which outputs: