Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

The output of find command is like


Now i want to get


from above string

share|improve this question
up vote 5 down vote accepted

Are you looking for that part of the path based on a fixed location from the left of the path or fixed depth from the right? If you are looking from the left you can do this easily with cut by using '/' as a field separator and grabbing the fourth field like this:

find ... | cut -d/ -f4
share|improve this answer
folder=$(basename $(dirname $path))

or, if you want to operate on the output of find (i.e. several paths, one per line)

find ... | awk -F/ '{print $(NF-1)}'
find ... | sed 's#.*/\([^/]*\)/[^/]*$#\1#'
share|improve this answer
Don't forget quotes around a variable expansion, so: $(basename "$(dirname \"$path\")") – alex Apr 20 '11 at 19:38
@alex, you don't need to escape the inner quotes -- they are protected by the parentheses (it's like a new "scope" for quotes). Fully quoted: folder="$(basename "$(dirname "$path")")" – glenn jackman Apr 20 '11 at 23:18
Blows my mind, but that's true :) – alex Apr 21 '11 at 6:16
The outermost quotes aren't necessary; variable assignment is one of the exceptions to word-splitting. You do still need to quote $(dirname) and $path, though. – grawity Apr 22 '11 at 11:25

I would use awk.

Something like:

find /home -name "abc.png" | awk -F"/" '{print $5}'
share|improve this answer

If you want "folder1", then type "folder1" ...

If you want the second-to-last path component, this works in both sh and bash:


(assuming $path contains the full path)

share|improve this answer

Here's my try:

find . -name abc.png -exec dirname {} \; |grep -o '[^/]*$'
share|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.