Bash: How to get part of the directory name?

How can I write a script that determines the directory the user is in, and displays that path up until a particular point?

Specifically, I need to find the text "packages" in the directory name, then I need to capture that directory and the one below it.

For example, if the user is in the /home/smith/packages/cat/abc/def directory, I want to display "/home/smith/packages/cat/".

If the user is in the /home/smith/packages/dog/hij/klm/nop qrs/tuv directory, I want to display "/home/smith/packages/dog/".

$ P=/home/smith/packages/cat/abc/def
$ echo $P | sed "s@\(.*/packages/[^/]*/\).*@\1@"
/home/smith/packages/cat/
1 Like

Thank you. It works. I have no freakin' idea how, but it works.

How can I get up to speed on this? Are those regular expressions?

Hi.

Yes, it's a regular expression.

Neo wrote a blog entry on a cool tool.

Aside from that, googling "regular expression" should give many good results (and, admittedly many not so good results :D).

What are the @ characters for? Most of the sed commands I have seen have the format:

sed "s/old/new/g" *

I can't find a reference to the @ character in the context of a regular expression or as sed syntax.

The @ is not a character part of the regex. It is the boundary symbol Scottn choose to build the substitution for the sed utility.
Usually sed uses `/' with the `s' as in sed 's/old/new/' but when you need to use the `/' as part of the regex, it can become a mess to understand, so to make it a little easier, sed allows you to use any other symbol and as long you are consistent it works.

sed 's:old:new:'
sed 's!old!new!'
sed 's@old@new@'

All of them do the same.

1 Like