Find directory name while traversing subdirectories

Hi,

I have a parent directory in which I have sub directories of different depth

/usr/usr1/user2/671
/usr/usr1/672
/usr/user2/user1/673
/usr/user2/user3/user4/674

And I need the names of all the directories that which starts only with 6 in a file.

Thanks,

Try

find /usr -name "6*" | sed 's/\(.*\)\/.*/\1/'
1 Like

Try:

find /usr -name "6*" -type f 2>/dev/null | awk -F "/" '{print $(NF-1)}'

Both the above commands are giving me only the first directory name from the parent directory where I search, like:

usr1
usr1
user2
user2

can you show the sample records?

Actually I need the following output:

671
672
673
674

But that is the filename ( not the directory name as you mentioned in your previous post)
Or they are?

try this:

find /usr -name "6*" -type f 2>/dev/null | awk -F "/" '{print $NF}'
1 Like

Strange, it works here (with Solaris 10):

$ find usr -name "6*" | sed 's/\(.*\)\/.*/\1/'
usr/usr1/user2
usr/usr1
usr/user2/user1
usr/user2/user3/user4

What OS are you using?

---------- Post updated at 15:56 ---------- Previous update was at 15:55 ----------

Ah, simultanous posting.

Try:

$ find usr -name "6*" | sed 's/\(.*\)\///'
671
672
673
674

If you are looking for the directory name which starts with 6, then

find /usr -name "6*" -type d 2>/dev/null | awk -F "/" '{print $NF}'

Thanks both the commands are working fine now.

@Anchal:

If you could explain the command in part for understanding purpose it would be great.

find /usr -name "6*" -type d 2>/dev/null 

Recursively Looking for the directories ( -type d ) which starts with 6 ( -name "6*" ) in /usr.

2>/dev/null is nullifying the error message (if any).

awk -F "/" '{print $NF}'

The find command output goes into awk. This uses "/" as a field delimiter (-F) and prints the last field from the path.

find /usr -type d -name '6*' 2>/dev/null | sed 's/.*\///'
1 Like

Thanks everybody for your reply