Why can't I use a command like this to find all the pdf files in a directory and subdirectories? How do I do it? (I'm using bash in ubuntu)

ls -R *.pdf

EDIT

How would I then go about deleting all these files?

link|improve this question
I believe this should belong in unix.stackexchange.com – Qosmo Feb 15 '11 at 14:35
feedback

3 Answers

up vote 9 down vote accepted

Why can't I use a command like this to find all the pdf files in a directory and subdirectories?

The wildcard *.pdf in your command is expanded by bash to all matching files in the current directory, before executing ls.


How do I do it? (I'm using bash in ubuntu)

find is your answer.

find . -name \*.pdf

is recursive listing of pdf files. -iname is case insensitive match, so

find . -iname \*.pdf

lists all .pdf files, including for example foo.PDF

Also, you can use ls for limited number of subfolders, for example

ls *.pdf */*.pdf

to find all pdf files in subfolders (matches to bar/foo.pdf, not to bar/foo/asdf.pdf, and not to foo.PDF).

If you want to remove files found with find, you can use

find . -iname \*.pdf -delete
link|improve this answer
Thanks for the clarification. And I didn't know about -iname. – Tomba Feb 15 '11 at 14:09
@Tomba: if this answered your question, you should accept it. – Olli Feb 15 '11 at 14:10
don't worry, I will, when I can in 9 minutes time – Tomba Feb 15 '11 at 14:11
2  
Don't put -r on the rm command, that adds recursion to it which find is already doing. – Matt H Feb 15 '11 at 14:18
4  
You shouldn't need to use -exec to delete the file. Find has a -delete argument that will delete any files it finds. – Herms Feb 15 '11 at 15:22
show 5 more comments
feedback

As others have said, find is the answer.

Now to answer the other part.

  • How would I then go about deleting all these files?

    find . -iname *.pdf -exec rm {} \;

Should do it.

link|improve this answer
1  
You need to quote your glob to keep it from being prematurely expanded. – Dennis Williamson Feb 15 '11 at 15:43
feedback

Use find instead of ls

find . -name '*.pdf'
link|improve this answer
feedback

Your Answer

 
or
required, but never shown

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