使用grep在一个很长的字符串中搜索一个词

Using grep to search for a word in a very long string

我有一个包含唯一长字符串的巨大文件。我需要在该文件中搜索特定的词。当然我不能使用 gedit 或类似的软件,因为它们塞住了。因此,解决方案可能是 grep。问题是如果单词匹配,它 returns 完整的字符串进入 shell ,所以我找不到单词所在的位置,也无法观察到其他附近的单词。

是否有任何特定的选项可以传递给 stop/pause grep shell 流(例如,匹配后一定数量的字符)一旦找到我的话?

使用-m NUM, --max-count=NUM选项:

$ grep -m 1 [pattern] [/path/to/file]

Stop reading a file after NUM matching lines. If the input is standard input from a regular file, and NUM matching lines are output, grep ensures that the standard input is positioned to just after the last matching line before exiting, regardless of the presence of trailing context lines. This enables a calling process to resume a search. When grep stops after NUM matching lines, it outputs any trailing context lines. When the -c or --count option is also used, grep does not output a count greater than NUM. When the -v or --invert-match option is also used, grep stops after outputting NUM non-matching lines.

使用 -o 选项 "Show only the part of a matching line that matches PATTERN."

示例:

% cat lorem
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.                                                                                                                                              
% grep -oE '.{20}fugiat.{20}' lorem
se cillum dolore eu fugiat nulla pariatur. Exc

编辑:@tripleee 建议使用 E 部分,以在匹配的两边填充。