0

ls -R lists files recursively and ls *.pdf lists all files ending with .pdf. My question is why ls does not combine these 2 functions into 1 e.g. ls -R \*.pdf to look for PDF files recursively. Of course, there is find and others. I am curious. Thanks

thlim
  • 103

1 Answers1

2

Because *.pdf is expanded by the shell to all the .pdf files in the current working directory and it's not relevant to the ls command you expect to take *.pdf as to look all .pdf files in any subdirectory; to get that work you need to enable the shell (in bash) globstar option and use ** in order to look/expand *.pdf in any sub-directories as well as current working directory, like below:

shopt -s globstar; ls -d -- **/*.pdf

Moreover, with using ls -R \*.pdf, you are looking for a single file matched literal *.pdf and -R here has no effect of looking for sub-directories (unless that *.pdf file is actually a directory) and that's just used to list subdirectories recursively. with that you can use ls with grep combination to filter .pdf files.

ls -bR |grep '\.pdf$'

but this doesn't guarantee it will report only files but will report directories with same ending pattern too.

and well, as you said and were aware, best option is to using find command.

find . -type f -name '*.pdf'
αғsнιη
  • 41,407
  • 1
    ls -bR |grep '\.pdf$' also won't work for files with newlines in their names. See Why not parse ls (and what to do instead)? – phuclv Mar 27 '21 at 10:52
  • @phuclv what version of ls do you use? with -b (or -Q or -q), filename with all newlines combine into single line and properly can filter. but as said find is best alternative and I'm aware of not parsing ls output thought. – αғsнιη Mar 27 '21 at 11:07
  • Still, what you get from that grep is not actually the name of a file, but some encoded variant of the name, like my\ nice\ndocument.pdf. Without decoding it (and knowing when it's needed to decode it), the string is useless. – Kusalananda Mar 27 '21 at 11:16
  • ahh, if that is the concern (parse the names then), yes, absolutely that's not the right option to use it. – αғsнιη Mar 27 '21 at 11:28