I often find myself changing directories using cd or using relative paths and wildcards to grep for a pattern down a directory tree. This could be done in one command line sequence using the find utility.
find /work –print xargs grep ‘[Ee]rror’
The command listing above uses find to print all the files under the /work directory. The output of the find utility was piped to the xargs utility. Quoting from Linux in a Nutshell 3rd Edition
xargs [options] [command]
Execute command (with any initial arguments), but read remaining arguments from standard input instead of specifying them directly. xargs passes these arguments in several bundles to command, allowing command to process more arguments than it could normally handle at once. The arguments are typically a long list of filenames (generated by ls or find, for example) that get passed to xargs via a pipe.
Xargs enables grep to find the pattern ‘[Er]rror’ in the files piped from the find command.
Another example:
find /work –type f –name ‘*.txt’ –print xargs grep –l ‘[Ee]rror’
in this example we are looking for the word Error or error in the files with extension .txt under the work directory. The –l switch used for grep just prints out the filenames where the pattern was found. The –type f switch for find limits our search to files. The –name switch limits our search to just files with .txt extension.
No comments:
Post a Comment