Code Snippet

Just another Code Snippet site

[Find] How-to

find . -name "*.java" -exec grep -ni <pattern_to_find> /dev/null {} \;

List only directories, max 2 nodes down that have “net” in the name

find /proc -type d -maxdepth 2 -iname '*net*'

Find all *.c and *.h files starting from the current “.” position.

find . \( -iname '*.c'  -o -iname '*.h' \) -print

Find all, but skip what’s in “/CVS” and “/junk”. Start from “/work”

find /work \( -iregex '.*/CVS'  -o -iregex '.*/junk' \)  -prune -o -print

Note -regex and -iregex work on the directory as well, which means
you must consider the “./” that comes before all listings.

Here is another example. Find all files except what is under the CVS, including
CVS listings. Also exclude “#” and “~”.

find . -regex '.*' ! \( -regex '.*CVS.*'  -o -regex '.*[#|~].*' \)

Find a *.c file, then run grep on it looking for “stdio.h”

find . -iname '*.c' -exec grep -H 'stdio.h' {} \;

sample output –> ./prog1.c:#include
./test.c:#include

Search a string in JAR file :

zipgrep "STRING_TO_FIND" file.jar

Search a string in multiple JAR files :

find JAR_FOLDER -name "*.jar" -exec zipgrep "STRING_TO_FIND" '{}' \;


7 thoughts on “[Find] How-to

  • Olivier says:

    Move all files older than 200 days :

    find . -type f -mtime +200 -exec mv '{}' /tmp \;
    
  • Olivier says:

    Delete all files older than 200 days :

     find . -type f -mtime +200 -print | xargs rm -rf
  • Olivier says:

    Delete folders from first depth older than 1 month

    find . -maxdepth 1 -type d -mtime +30 -print | xargs rm -rf
    
  • Olivier says:

    Find & dos2unix

    find . -type f -print0 | xargs -0 dos2unix
  • Olivier says:

    Find all files expect from a specific sub folder (and add it to Git)

    find -name '*.json' -not -path '*/node_modules/*' -type f -print0 | xargs -0 git add
  • Find all files owned by a specific user :

    find . -user root -type f
    
  • Find (with exclude pattern) and copy files/folder with structure preservation:

    find ./ ! -path "*/BCK/*" ! -path "*/deprecated/*" | cpio -p -dumv /path/to/new/folder/.
    

Leave a Reply to Olivier Cancel reply

Your email address will not be published. Required fields are marked *