Search code examples
bashunixsedpalindrome

Find palindrome without loops using sed


I would like to determine if a string is palindrome or not.
Let's say that I have file like this:
abcccba
abcccccccccccccccccccccccba

alfabetaalfa

I would like to check every line of this file and say "PALINDROME" every time line is a palindrome. The problem is i cannot use matching like ([0-9])([0-9])/2/1 because i dont know how long the word will be. I think that i should patternbuffer somehow.

Searching stackoverflow to find some hints, i have found this: sed -r 'h;s/[^[:alpha:]]//g;H;x;s/\n/&&/;ta;:a;s/\n(.)\n(.)/\n\2\1\n/;ta;G;/\n(.)\n\n\1$/I;d' $1

The problem is that it does not exactly work as it should and I have no idea how to use it to print specific words like "PALINDROME" or "NOT A PALINDROME".

Thank you so much for any help.

EDIT: of course by "not using loops" i mean common loops. Jumping to labels is okay.


Solution

  • You don't have to use sed:

    xxx="rrrtttrrr"
    
    if [ $xxx == `echo $xxx| rev` ]; then
        echo "PALINDROME"
    else
        echo "NOT A PALINDROME"
    fi
    

    Sed version could be found here:

    #! /bin/sed -f
    # Laurent Le Brun <laurent [at] le-brun.eu> - 2007
    
    :loop
    s/^\(.\)\(.*\)\1$/\2/
    t loop
    /...*/ {
        i\
     no
        b end
    }  
    i\
     yes
    
    :end
    d