Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

The output of find command is like

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

Now i want to get

folder1

from above string

share|improve this question
add comment

5 Answers 5

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
add comment
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#'
share|improve this answer
    
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")")" –  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
add comment

I would use awk.

Something like:

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

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)

share|improve this answer
add comment

Here's my try:

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

Your Answer

 
discard

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.