How to list specific type of files in recursive directories in shell?
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?
Solution 1:
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.
Solution 2:
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
Solution 3:
find . | grep "\.doc$"
This will show the path as well.