6

I need to grep all lines that start and end with the same substring of at least 4 letters. The substrings can't overlap.

So imagine we have the input:

ABCDOOOPABCD
BBBBOLPOKBBBB
ACLMDJKAC
12345---12345
ABCD

Then the output should be:

ABCDOOOPABCD
BBBBBOLPOKBBBBB
12345---12345
1
  • Should whitespace be ignored or not? For instance, should this string match: ' ABCXXXXABC '?
    – terdon
    Commented Oct 18, 2022 at 11:12

1 Answer 1

17

Using grep with a basic regular expression:

grep -x '\(.\{4,\}\).*\1' file

Using grep with an extended regular expression (-E):

grep -Ex '(.{4,}).*\1' file

Using -x option for only full line matches.

An explanation for the regular expression:

  • (.{4,}) A group of at least 4 characters
  • .* From 0 to an infinite numbers of characters
  • \1 A backreference to the first captured group (in this case (.{4,}))
0

You must log in to answer this question.

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