How can I search my entire Linux filesystem for all python files (files with extension .py
)? I know I can do find -name filename
but how can I do it for file type?

- 197,895
- 55
- 485
- 740
3 Answers
sudo find / -name "*.py"
You only need sudo
to avoid Permission denied
s (since you're searching from the root).

- 173
-
2You need to be careful with 'bare' globs in situations like this: if there happens to be a file or files in the current directory that match
*.py
the shell will expand the glob and pass the result of that to thefind
command. Bottom line: quote or escape any such patterns i.e. use"*.py"
or'*.py'
or\*.py
– steeldriver Jun 10 '16 at 02:13
Not all python files will have the file extension .py
- Try running grep -rni python /usr/bin
for example). Most of these scripts will have a 'shebang' (or hashbang) line (e.g. #!/usr/bin/env python
, #!/usr/bin/python2.7
). This informs the interpreter of the script which program needs to be used to run it, and you could search for this to find python files
However, you can also use the file's mimetype (usually along the lines of text/x-python
) to find it:
find / -type f | while read in ; do if file -i "${in}" | grep -q x-python ; then echo "${in}" ; fi ; done
Where /
is your intended search directory.
With find
you could also add the -executable
option to look for only executable files. Also the use of -type f
restrict find to look only for files - you could change this and then show symbolic links etc as well (some scripts are contained in /usr/lib
etc and symlinked to /usr/bin/
etc). Many more options are available, you can see these by running man find
.
file
should be able to guess the filetype even if the file has no extension etc (using the shebang line etc) - see here.
To removed any find: ‘/.../FILE’: Permission denied
etc errors, you can run the script as root (using sudo bash -c "COMMAND"
, opening a shell with sudo su
etc), and/or simply append 2>/dev/null
to the find command.
-
3Yes ! Exactly that ! Linux/Unix doesn't care about extensions , and that's exactly the way I'd approach this question. I also think
find
+-exec
flag would be a better alternative, and just pipe output togrep
orawk
. That will bring down the line to two pipes only. – Sergiy Kolodyazhnyy Jun 10 '16 at 03:14 -
2If you really are going to
find | while read
, then dofind … -print0 | while IFS= read -d '' -r in
. See http://mywiki.wooledge.org/ParsingLs#line-108 – muru Jun 10 '16 at 03:16 -
Thanks, I knew someone would say 'u could do this' :) , I didn't k now the parsing Ls thing would come up :D You can add your own versions if you want... I can't right now – Wilf Jun 10 '16 at 03:28
-
@Wilf well, you are examining every file in the system. Who knows what filenames will come up. – muru Jun 10 '16 at 03:38
.py
? – Wilf Jun 10 '16 at 02:31