Bash palindrome grep loop if then otherwise missing '
source link: https://www.codesd.com/item/bash-palindrome-grep-loop-if-then-otherwise-missing.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
Bash palindrome grep loop if then otherwise missing '
My Syst admin prof just started teaching us bash and he wanted us to write a bash script using grep to find all 3-45 letter palindromes in the linux dictionary without using reverse. And im getting an error on my if statement saying im missing a '
UPDATED CODE:
front='\([a-z]\)'
front_s='\([a-z]\)'
numcheck=1
back='\1'
middle='[a-z]'
count=3
while [ $count -ne "45" ]; do
if [[ $(($count % 2)) == 0 ]]
then
front=$front$front_s
back=+"\\$numcheck$back"
grep "^$front$back$" /usr/share/dict/words
count=$((count+1))
else
grep "^$front$middle$back$" /usr/share/dict/words
numcheck=$((numcheck+1))
count=$((count+1))
fi
done
You have four obvious problems here:
First about a misplaced and unescaped backslash:
back="\\$numcheck$back" # and not back="$numcheck\$back"
- Second is that you only want to increment
numcheck
ifcount
is odd. Third: in the line
front=$front$front
you're doubling the number of patterns in
front
! hey, that yields an exponential growth, hence the explosion Argument list too long. To fix this: add a variable, say,front_step
:front_step='\([a-z]\)' front=$front_step
and when you increment
front
:front=$front$front_step
With these fixed, you should be good!
The fourth flaw is that grep
's back-references may only have one digit: from man grep
:
Back References and Subexpressions
The back-reference \n, where n is a single digit, matches the substring
previously matched by the nth parenthesized subexpression of the
regular expression.
In your approach, we'll need up to 22 back-references. That's too much for grep
. I doubt there are any such long palindromes, though.
Also, you're grepping the file 43 times… that's a bit too much.
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK