Languages/shell/find
From UIT
(Difference between revisions)
Marc.pignat (Talk | contribs) (→Finding files containing a string) |
Marc.pignat (Talk | contribs) |
||
Line 46: | Line 46: | ||
== Removing empty directories == | == Removing empty directories == | ||
find . -type d -empty -print -delete | find . -type d -empty -print -delete | ||
+ | |||
+ | = Traps = | ||
+ | == find: missing argument to `-exec' == | ||
+ | * The <code>-exec</code> command must be terminated by " \;", so the "\;" is missing or the space. |
Latest revision as of 12:11, 17 February 2017
The find
command
This command can be used to find files (or directories) recursively.
Finding all files and directories starting from the current directory
find .
Will display all files and directories below the current directory.
Finding all files and directories in a directory
find /etc
Will display all files and directories below /etc.
Finding all files and directories in many directory
find /etc /home
Will display all files and directories below /etc and /home (in that order).
Finding only files in a directory
find /etc -type f
Will display all files (no directories) below /etc.
Finding files with a suffix
find /etc -type f -name "*.conf"
Will find all files with name ending by .conf below /etc.
- Warning: Don't forget the double quotes (") around the file name
- Warning: find is case sensitive, if you also want files with "*.Conf", use the
-iname
Finding files containing a string
find . -type f -exec grep -q "heivs/error\.h" {} \; -print
Will find all files containing heivs/error.h
- The
-exec
command will execute grep on every file found by file, and evaluates it's return value. - The
-print
command is necessary to display the file that match the-exec
command. - The
{}
is the filename given by find to grep. - The
\;
is the end of the-exec
command. - Warning there is always a space before
\;
- Warning grep uses regular expressions for matching, so the dot (.) must be escaped
Editing files containing a string
EDITOR=vi find . -type f -exec grep -q "heivs/error\.h" {} \; -exec $EDITOR {} \;
- Warning Set
$EDITOR
to your preferred editor
Finding files with any of 2 suffixes
find . -type f -name "*.h" -o -name "*.c"
- The
-o
parameter means OR.
Removing empty directories
find . -type d -empty -print -delete
Traps
find: missing argument to `-exec'
- The
-exec
command must be terminated by " \;", so the "\;" is missing or the space.