Take the 2-minute tour ×
Super User is a question and answer site for computer enthusiasts and power users. It's 100% free, no registration required.

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.

share|improve this question
add comment

3 Answers

$ uniq -d <<< 'STRING1
> STRING2
> STRING1
> STRING1
> STRING1
> STRING3
> STRING4
> STRING4
> STRING5
> STRING6
> STRING5'
STRING1
STRING4
share|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
add comment
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
share|improve this answer
add comment

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
share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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