22

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?

Tomba
  • 395
  • 1
  • 3
  • 8

3 Answers3

26

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
Olli
  • 7,571
  • 3
  • 34
  • 47
  • 2
    Just in case you want an output similar to the `ls -l` command, showing file size, ownership, date, etc., you can use `find` with the `-ls` option, e.g. `find . -name \*.pdf -ls` – RFVoltolini Aug 01 '16 at 10:48
  • then how would you list them by file size? – CpILL Aug 11 '21 at 21:58
3

Use find instead of ls

find . -name '*.pdf'
vartec
  • 752
  • 1
  • 5
  • 15
2

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.

hookenz
  • 4,043
  • 3
  • 32
  • 46