0

The output of find command is like

/home/user/test/folder1/abc.png

Now i want to get

folder1

from above string

5

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
3
path=/home/user/test/folder1/abc.def
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#'
4
  • Don't forget quotes around a variable expansion, so: $(basename "$(dirname \"$path\")")
    – alex
    Apr 20 '11 at 19:38
  • 1
    @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")")" 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.
    – user1686
    Apr 22 '11 at 11:25
1

I would use awk.

Something like:

find /home -name "abc.png" | awk -F"/" '{print $5}'
0

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


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

dir=${path%/*}
dir=${dir##*/}

(assuming $path contains the full path)

0

Here's my try:

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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