0

There's another (unanswered) question with this same title but aimed at windows. I want to know how to do this in linux.

I have this: find ./ -type f -exec grep -H 'mystring' {} \;, which will find the string and return the whole line... but I want to use this on a file which only contains one long line, so I'd like to be able to receive just the context before and after the found string.

1
  • "on a file which only contains one long line" – Investigating the reason may lead to better solutions. E.g. maybe the file is in fact a sequence of lines, but with null character (not newline character) being the terminator; in such case GNU grep -z would be a good start. Jan 27, 2022 at 16:26

1 Answer 1

1

Use grep -o that will show you matching parts instead of whole lines. If there are two or more matches in a line then they will be printed on separate output lines.

To see mystring with neighboring characters, you need to expand the pattern so it matches the neighboring characters as well. The following command will search for (and print) mystring with up to 10 characters to the left and up to 10 characters to the right:

grep -oE '.{0,10}mystring.{0,10}'

(without -E you would need .\{0,10\}mystring.\{0,10\} which does not look that nice).

Notes and quirks:

  • -o is not portable, your grep may or may not support it. GNU grep does support -o.

  • Do not try to match exactly 10 characters. Allowing less is crucial when mystring occurs near the beginning or near the end of a line. Note .{0,10} is greedy, so you will get as close to 10 as possible.

  • Inside mystring 2345 mystring … the command will find one occurrence of the pattern, not two. You will see mystring 2345 myst and then the search for the next occurrence will start at ring, missing one match.

  • Similarly mystring 234567890foo mystring … will print mystring 234567890 and the search for the next occurrence will start at foo. It will find the second mystring, but it will print foo mystring …, not 567890foo mystring ….

  • If your grep supports -r (meaning "read all files under each directory, recursively") then maybe you don't need find. Example:

    grep -rHoE '.{0,10}mystring.{0,10}' ./
    

    find will be useful if you want to perform additional tests though.

You must log in to answer this question.

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