How to list specific type of files in recursive directories in shell?

后端 未结 7 639
無奈伤痛
無奈伤痛 2021-01-31 15:26

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 th

相关标签:
7条回答
  • 2021-01-31 15:40

    Similarly if you prefer using the wildcard character * (not quite like the regex suggestions) you can just use ls with both the -l flag to list one file per line (like grep) and the -R flag like you had. Then you can specify the files you want to search for with *.doc I.E. Either

    ls -l -R *.doc
    

    or if you want it to list the files on fewer lines.

    ls -R *.doc
    
    0 讨论(0)
  • 2021-01-31 15:42

    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
    
    0 讨论(0)
  • 2021-01-31 15:43

    If you have files with extensions that don't match the file type, you could use the file utility.

    find $PWD -type f -exec file -N \{\} \; | grep "PDF document" | awk -F: '{print $1}'

    Instead of $PWD you can use the directory you want to start the search in. file prints even out he PDF version.

    0 讨论(0)
  • 2021-01-31 15:44

    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.

    0 讨论(0)
  • 2021-01-31 15:48

    Some of the other methods that can be used:

    echo *.{pdf,docx,jpeg}

    stat -c %n * | grep 'pdf\|docx\|jpeg'

    0 讨论(0)
  • 2021-01-31 15:48
    find . | grep "\.doc$"
    

    This will show the path as well.

    0 讨论(0)
提交回复
热议问题