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

蹲街弑〆低调 提交于 2020-01-11 15:42:01

问题


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?


回答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.




回答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



回答3:


Some of the other methods that can be used:

echo *.{pdf,docx,jpeg}

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




回答4:


find . | grep "\.doc$"

This will show the path as well.




回答5:


We had a similar question. We wanted a list - with paths - of all the config files in the etc directory. This worked:

find /etc -type f \( -iname "*.conf" \)

It gives a nice list of all the .conf file with their path. Output looks like:

/etc/conf/server.conf

But, we wanted to DO something with ALL those files, like grep those files to find a word, or setting, in all the files. So we use

find /etc -type f \( -iname "*.conf" \) -print0 | xargs -0 grep -Hi "ServerName"

to find via grep ALL the config files in /etc that contain a setting like "ServerName" Output looks like:

/etc/conf/server.conf: ServerName "default-118_11_170_172"

Hope you find it useful.

Sid




回答6:


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


来源:https://stackoverflow.com/questions/3528460/how-to-list-specific-type-of-files-in-recursive-directories-in-shell

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!