To find which files in the current directory contains specific string I would command find . -type f -print0 | xargs -0 grep -ial <word>. However this only shows path to file. How do I print the result in format, which prints path to file, line number(s), the matching line(s) (limited by parameter) with n heading and tailing lines, and newline before next result? What is the best resource to learn power use and tips of linux search and text manipulation tools?

  • 1
    grep -iarn word /some/dir Sep 20, 2016 at 4:38
  • For text handling you must get familiar with regular expressions, the regex tag. Note the new stackexchange documentation feature.
    – meuh
    Sep 20, 2016 at 10:47

1 Answer 1

grep -iarn -C3 word .

This will search the current directory and all subdirectories (just like your find . -type f -print0 command), and show you the lines in those files matching "word" with three leading and trailing lines of context, and with the filename and line numbers labeling each line.

Instead of a blank line between matches, grep gives you pairs of lines with only -- on them. If you really need a blank line because you are feeding the output of this to some other program, you can use this version:

grep -iarn -C3 word . | uniq | sed -e 's/^--$//'

As far your question on how to learn power tips, the Unix man pages are fairly dry reading, but skimming through the man page for some of the common tools is very educational. I also in particular recommend learning Perl if you do a significant amount of text manipulation in Linux or UNIX.

  • Recent versions of GNU grep should support a blank-line context separator directly using --group-separator='' Sep 20, 2016 at 7:04

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .