Saurabh Agrawal
Saurabh Agrawal

Reputation: 75

Get substring before last occurrence of a word in shell script

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

Answers (1)

twalberg
twalberg

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

Related Questions