Python for Network Engineers

Using Linux Find Command

by: George El., November 2018, Reading time: 3 minutes

The find command allows to find files based on various criteria, some of which are:

  • maxdepth : the number of directories depth
  • type f : files
  • type d: directories
  • name : the name of the files like “*.txt”
  • iname : same as above but ignore case
  • size +10M : find files overs 10Mbytes
  • size -5k: find files less than 5Kbytes
  • size +1G : find files larger than 1gig
  • mtime -7 : shows files modified last 7 days
  • mtime -30 : shows files modified last 30 days
  • ok prompt the user for permission


copy all files from /home/geo/temp to /tmp (you can also use xargs)

find /home/geo/temp –exec cp {} /tmp \;

send all errors to /dev/null

find / -name *.log 2> /dev/null 

execute a command for each file found. In this example delete each file

find . -name "*.txt" 2>/dev/null -exec rm {} \;

delete all logs older than 30 days, -ok will prompt before executing

find /var -type f -name "*log*" -mtime -30 2>/dev/null -exec rm -i {} \;
find /var -type f -name "*log*" -mtime -30 -exec rm -i {} \;
find /var -type f -name "*log*" -mtime -30 -ok rm -i {} \;

find total size of files

find . -name "*.mp3" -exec stat -c %s {} \; | paste -sd+ | bc

you can combine with xargs

find . -name "*.mp3" | xargs stat -c %s | paste -sd+ | bc

when you have files with spaces there will be an error. To avoid this you instruct find to use a null character instead of space using -print0 and xargs to use null using -0. So lets see an example

$ ls
file1.txt  file2.txt  file with spaces.txt

lets try first without -print0

$ find . -name "*.txt" | xargs stat -c %s
stat: cannot stat './file': No such file or directory
stat: cannot stat 'with': No such file or directory
stat: cannot stat 'spaces.txt': No such file or directory

the 0 is ok, because these files are empty but you see we got an error on the first file, because it though it was three files. to avoid this, we will use -print0 and -0

$ find . -name "*.txt" -print0 | xargs -0 stat -c %s

now everything works ok

another thing to mention is that when you use glob characters like *, ? you should quote them, otherwise the shell will perform expansion and will cause an error on find. example

$ set -x $ find . -name *.txt

  • find . -name file01.txt file02.txt file03.txt file04.txt file05.txt file06.txt file07.txt file08.txt file09.txt file10.txt find: paths must precede expression: file02.txt Usage: find [-H] [-L] [-P] [-Olevel] [-D help|tree|search|stat|rates|opt|exec|time] [path…] [expression] $ find . -name “*.txt”
  • find . -name ‘*.txt’ ./file01.txt ./file02.txt ./file03.txt ./file04.txt ./file05.txt ./file06.txt ./file07.txt ./file08.txt ./file09.txt ./file10.txt
comments powered by Disqus