BASH Palindrome Checker

前端 未结 5 1921
[愿得一人]
[愿得一人] 2021-01-24 19:14

This is my first time posting on here so bear with me please.

I received a bash assignment but my professor is completely unhelpful and so are his notes.

Our assig

5条回答
  •  广开言路
    2021-01-24 19:55

    Why use grep? Bash will happily do that for you:

    #!/bin/bash
    
    is_pal() {
        local w=$1
        while (( ${#w} > 1 )); do
            [[ ${w:0:1} = ${w: -1} ]] || return 1
            w=${w:1:-1}
        done
     }
    
     while read word; do
         is_pal "$word" && echo "$word"
     done
    

    Save this as banana, chmod +x banana and enjoy:

    ./banana < /usr/share/dict/words
    

    If you only want to keep the words with at least three characters:

    grep ... /usr/share/dict/words | ./banana
    

    If you only want to keep the words that only contain lowercase and have at least three letters:

    grep '^[[:lower:]]\{3,\}$' /usr/share/dict/words | ./banana
    

提交回复
热议问题