Reputation: 75
I have a string /abc/xyz/def/xyz/1234/lmn/xyz/7890/uvw
in Linux.
I want to extract the substring before the last occurrence of the string xyz
using shell script.
Example:
Input:
/abc/xyz/def/xyz/1234/lmn/xyz/7890/uvw
Output:
/abc/xyz/def/xyz/1234/lmn
I searched online and there are solutions with single character separator, but I couldn't figure out how to get it working with a string separator like xyz
.
Upvotes: 5
Views: 11547
Reputation: 62389
How about this:
$ x=/abc/xyz/def/xyz/1234/lmn/xyz/7890/uvw
$ echo ${x%xyz*}
/abc/xyz/def/xyz/1234/lmn/
$ echo ${x%/xyz*}
/abc/xyz/def/xyz/1234/lmn
If you really don't want the /
before the last xyz
, then the second echo should be what you're looking for; if leaving the trailing /
is acceptable, the first does that.
Upvotes: 14