close
如何在給定的目錄中遞迴地搜尋檔案
Problem:
Find my_search_pattern in *all* files of /directory/to/search and *all*
directories beneath it. Take special care for directories with blanks
in their names. Your solution must work even if there are thousands of
files to check. This means that solutions that are in principle
correct, but give errors of type:
will NOT be accepted!
Solution:
The pipe to xargs will take care of an excessive number of files automatically - if there are too many of them, it will process them through grep and then will continue to process the rest!
The -print0 option tells find to append a 0 after each filename, the -0 option to xargs tells it to delimit filenames by 0 and not by blank. Thus we are able to process files with blanks in their names. It has the same syntax as grep and comes with a rudimentary help function which outputs the syntax and an example if you call it without arguments. I use grepdir quite often. Here it is:
Just type "grepdir" or "grepdir -h" to get a help message.

Code: |
Argument list too long |
will NOT be accepted!

Code: |
/usr/bin/find /directory/to/search -type f -print0 | /usr/bin/xargs -0 /usr/bin/grep my_search_pattern |
The pipe to xargs will take care of an excessive number of files automatically - if there are too many of them, it will process them through grep and then will continue to process the rest!
The -print0 option tells find to append a 0 after each filename, the -0 option to xargs tells it to delimit filenames by 0 and not by blank. Thus we are able to process files with blanks in their names. It has the same syntax as grep and comes with a rudimentary help function which outputs the syntax and an example if you call it without arguments. I use grepdir quite often. Here it is:
Code: |
#! /bin/sh # # /usr/local/bin/grepdir # # Author: Chris Karakas # http://www.karakas-online.de # # Searches the files of directory DIR recursively for # the expression EXP, excluding the contents of EXCLUDE_DIR # from the search, if any. # # Usage: grepdir EXP DIR [EXCLUDE_DIR] # Help function # function help() { cat <<-EOF Usage: grepdir EXP DIR [EXCLUDE_DIR] Searches the files of directory DIR recursively for the expression EXP, excluding the contents of EXCLUDE_DIR from the search, if any. -h, --help Display this help text EOF } # Check arguments and issue a help statement, if wrong # if [ $# -eq 0 ]; then help exit 1 elif [ $1 = "-h" -o $1 = "--help" ]; then help exit 0 elif [ $# -eq 1 -o $# -gt 3 ]; then help exit 1 fi FIND="/usr/bin/find" XARGS="/usr/bin/xargs" GREP="/usr/bin/grep" # Program name PN=${0##*/} arg1=$1 shift if [[ X"$2" = X"" ]]; then echo "$PN: running $FIND $1 -type f -print0 | $XARGS -0 $GREP $arg1" $FIND $1 -type f -print0 | $XARGS -0 $GREP $arg1 else echo "$PN: running $FIND $1 -path $2 -prune -o -type f -print0 | $XARGS -0 $GREP $arg1" $FIND $1 -path $2 -prune -o -type f -print0 | $XARGS -0 $GREP $arg1 fi |
Just type "grepdir" or "grepdir -h" to get a help message.
全站熱搜