Difference between revisions of "Find"

From Useful Things
Jump to: navigation, search
m
Line 20: Line 20:
 
<code>-print0</code> print the full file name on the standard output, followed by a null character (instead of the newline character that -print uses)<br />
 
<code>-print0</code> print the full file name on the standard output, followed by a null character (instead of the newline character that -print uses)<br />
 
<code>-0</code> input items are terminated by a null character instead of by whitespace, and the quotes and backslash are not special (every character is taken literally)
 
<code>-0</code> input items are terminated by a null character instead of by whitespace, and the quotes and backslash are not special (every character is taken literally)
 +
 +
== For each directory, set the directory mtime to the oldest file's mtime ==
 +
<pre>
 +
oldest() { local file oldest; for file in "${1:-.}"/*; do [ "$file" -ot "$oldest" -o -z "$oldest" ] && oldest=$file; done; touch -r "$oldest" "$0";
 +
export -f oldest
 +
</pre>
 +
<syntaxhighlight lang="bash">
 +
find . -type d -exec sh -c 'oldest "$0"' {} \;
 +
</syntaxhighlight>

Revision as of 11:03, 1 July 2015

Between dates

find / -newermt "27 Dec 2013" ! -newermt "1 Jan 2014"

-newermt newer than specified modification time
! invert proceeding condition

Several matches

find / -xdev \( -name .DS_Store -o -name ._.DS_Store \)

-xdev stay on the current filesystem
-o logical OR, use parentheses for clarity - must be escaped in bash

Find files and do something with each

find . -type f -print0 | xargs -0 <command>

-print0 print the full file name on the standard output, followed by a null character (instead of the newline character that -print uses)
-0 input items are terminated by a null character instead of by whitespace, and the quotes and backslash are not special (every character is taken literally)

For each directory, set the directory mtime to the oldest file's mtime

oldest() { local file oldest; for file in "${1:-.}"/*; do [ "$file" -ot "$oldest" -o -z "$oldest" ] && oldest=$file; done; touch -r "$oldest" "$0";
export -f oldest
find . -type d -exec sh -c 'oldest "$0"' {} \;