All,
I have a file where strings appear on each line in following format:

STRING1  
STRING2  
STRING1  
STRING1  
STRING1   
STRING3  
STRING4  
STRING4  
STRING5  
STRING6  
STRING5 

I want to find which strings appear consecutively in the file, using bash script. For e.g., in the above example, STRING1 and STRING4 appear consecutively and should be there in the output. Note, even though STRING5 appears twice, it isn't appearing consecutively.

I don't want to sort the file as the file size would be normally large and that would add overhead. The user would supply the string and the script would says if the string appears consecutively in the file.

FYI, the strings might have unwanted spaces after them.

link|improve this question

71% accept rate
feedback

3 Answers

$ uniq -d <<< 'STRING1
> STRING2
> STRING1
> STRING1
> STRING1
> STRING3
> STRING4
> STRING4
> STRING5
> STRING6
> STRING5'
STRING1
STRING4
link|improve this answer
Hey Ignacio, Thanks for the response. I have tried the uniq command.Sometimes the strings might have spaces after them and in that case the uniq command fails to find the consecutive appearing strings. – smokinguns Oct 12 '11 at 6:19
2  
So then shove them through a program that strips trailing spaces. – Ignacio Vazquez-Abrams Oct 12 '11 at 6:20
sed 's/ \+$//' – ceving Oct 16 '11 at 17:03
feedback
awk -v "key=STRING4" '
    $1 == key && $1 == prev {
        print key " appears on consecutive lines on line " NR
        found=1
        exit 0
    } 
    {prev = $1}
    END {if (! found) {print key " does not appear on consecutive lines"; exit 1}}
' filename
link|improve this answer
feedback

What about read and string compares? Seems like the easiest solution to me.

while read line; do 
    if [ "$line" == "$temp" ]; then 
        echo "$line"; 
    fi; 
    temp=$line; 
done < test.txt
link|improve this answer
feedback

Your Answer

 
or
required, but never shown

Not the answer you're looking for? Browse other questions tagged or ask your own question.