Difference between revisions of "Grep"
Jump to navigation
Jump to search
(One intermediate revision by the same user not shown) | |||
Line 19: | Line 19: | ||
If necessary, use the command from [[Find#Sorting_by_mtime]] to search on files in date order: | If necessary, use the command from [[Find#Sorting_by_mtime]] to search on files in date order: | ||
+ | |||
+ | <syntaxhighlight lang=bash> | ||
+ | find … -printf '%T@ %p\0' | sort -zk 1n | sed -z 's/^[^ ]* //' | xargs -0i grep -HR 'pattern' {} | ||
+ | </syntaxhighlight> | ||
<syntaxhighlight lang=bash> | <syntaxhighlight lang=bash> | ||
Line 25: | Line 29: | ||
sed -z 's/^[^ ]* //' | | sed -z 's/^[^ ]* //' | | ||
xargs -0i grep -HR 'pattern' {} | xargs -0i grep -HR 'pattern' {} | ||
+ | </syntaxhighlight> | ||
+ | |||
+ | ===List files containing STRING in first SIZE bytes of the file=== | ||
+ | |||
+ | <syntaxhighlight lang=bash> | ||
+ | find … -type f -exec \ | ||
+ | bash -c ' | ||
+ | grep -q "STRING" < <(head -c SIZE "$1") && | ||
+ | printf '%s' "$1" && | ||
+ | echo | ||
+ | ' _ {} \; | ||
</syntaxhighlight> | </syntaxhighlight> |
Latest revision as of 04:25, 17 August 2017
Include or exclude filename of matched file
-H, --with-filename # Default if there are multiple files to search -h, --no-filename # Default if there is only one file to search (or stdin)
grep with find
Given the common grep
command
grep -R 'pattern' *
a corresponding find -exec
command should add -H
to include the filename prefix in the results. (This is needed because the filenames are given one at a time.)
find … -exec grep -HR 'pattern' {} \;
If necessary, use the command from Find#Sorting_by_mtime to search on files in date order:
find … -printf '%T@ %p\0' | sort -zk 1n | sed -z 's/^[^ ]* //' | xargs -0i grep -HR 'pattern' {}
find … -printf '%T@ %p\0' |
sort -zk 1n | # 1n for oldest first, 1nr for newest first
sed -z 's/^[^ ]* //' |
xargs -0i grep -HR 'pattern' {}
List files containing STRING in first SIZE bytes of the file
find … -type f -exec \
bash -c '
grep -q "STRING" < <(head -c SIZE "$1") &&
printf '%s' "$1" &&
echo
' _ {} \;