views:

40

answers:

2

How can we find specific type of files i.e. doc pdf files present in nested directories.

command I tried:

$ ls -R | grep .doc

but if there is a file name like alok.doc.txt the command will display that too which is obviously not what I want. What command should I use instead?

+6  A: 

ls command output is mainly intended for reading by humans. For advanced querying for automated processing, you should use more powerful find command:

find /path -type f \( -iname "*.doc" -o -iname "*.pdf" \) 

As if you have bash 4.0++

#!/bin/bash
shopt -s globstar
shopt -s nullglob
for file in **/*.{pdf,doc}
do
  echo "$file"
done
ghostdog74
It's **/*.pdf **/*.doc - you are not recursing into the the sub directories without it
Petesh
its actually double asterix
ghostdog74
You can do `ls **/*.{pdf,doc}` or `for file in **/*.{pdf,doc}`
Dennis Williamson
yes of course. totally forgot about brace expansion
ghostdog74
Wow, I typed in three asterisks and it replaced it with one - something to know in the future.
Petesh
+1  A: 

If you are more confortable with "ls" and "grep", you can do what you want using a regular expression in the grep command (the ending '$' character indicates that .doc must be at the end of the line. That will exclude "file.doc.txt"):

ls -R |grep .doc$

More information about using grep with regular expressions in the man.

Benoit Courtine