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?
- 207,228
- 173
- 1
- 1
- 3
3 Answers
sudo find / -name "*.py"
You only need sudo to avoid Permission denieds (since you're searching from the root).
- 173
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.