0

I have a text file and I want to print only the lines that have all their characters are consecutively reapeated at least two times or more. FOR EXAMPLE THE INPUT:

11
AAA
555227777
BBhh@@222
baabbb
1112
212211
baa
22333445
322113

 The output should be:

11
AAA 
555227777
BBhh@@222

 The output contains only these four lines because  they have only consecutively duplicate characters in order.

I have tried this code

grep '\(^\| \)\([   ])\2\1\($\| \)' INFILE

But its not working exactly.

1
  • 1
    grep -E '^((.)\2+)+$' should get you your desired results. Oct 18, 2018 at 19:13

2 Answers 2

3
 sed -En 'h;:a;s/^(.)\1+//;ta;/^$/{x;p}' file

with commentary

sed -E -n '
    h            # store a copy of the line
    :a           # set label "a"
    s/^(.)\1+//  # from the start of the line, remove sequences of 2 or more repeated chars
    ta           # *if the pattern matched* jump to "a"
    /^$/ {       # if empty string:
        x        #   retrieve the original line
        p        #   and print it
    }
' file
4
  • glenn jackman thank you very much for your answer.
    – Ahmed
    Oct 18, 2018 at 17:38
  • Could you please explain this command -En 'h;:a;s/^(.)\1+//;ta;/^$/{x;p}' for me?
    – Ahmed
    Oct 18, 2018 at 17:43
  • It's exactly the same as the commented version Oct 18, 2018 at 17:43
  • Yes its it, could you please explain your command factors?
    – Ahmed
    Oct 18, 2018 at 18:30
2

One way , using Gnu sed, could be:

sed -Ee '/^((.)\2+)+$/!d'  input.txt
3
  • @@Rakesh Sharma thanks for your command , could you please modify it for me to print only the lines with all consecutively repeated charactets three times exactly no more no less like 111444 or bbbcccfff111
    – Ahmed
    Oct 18, 2018 at 19:42
  • 1
    perl -lne 'print if /^((.)\2\2(?!\2))+$/' Oct 18, 2018 at 20:09
  • Thanks Rakesh Sharma , i have solved it by modifying your previous command to sed -Ee '/^((.)\2{2})+$/!d' input.txt.
    – Ahmed
    Oct 18, 2018 at 20:22

You must log in to answer this question.

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