Before posting went thru almost all suggestions in stackoverflow wizard but non of them were for bash most in c#. The exercise is for c language.
The problem.
Write a program that reverses the words in a sentence:
Enter a sentence: you can cage a swallow can't you? Reversal of sentence: you can't swallow a cage can you?Use a loop to read the characters one by one and store them in a one-dimensional char array. Have the loop stop at a period, question mark, or exclamation point (the "terminating character"), which is saved in a separate char variable. Then use a second loop to search backward through the array for the beginning of the last word. Print the last word, then search backward for the next-to-last word. Repeat until the beginning of the array is reached. Finally, print the terminating character.
I tried using tac with tr to swap spaces with newlines for tac to read but that didnt work for me. Eventually solved it with while loops. Would like to know if there are shorter ways to implement same thing but without awk or sed.
my code:
#!/bin/bash
#set -x
read -rp "Enter a sentence: " -a sentence
if [ -z "$sentence" ]; then
echo "empty..exiting"
exit 1
fi
terminator=""
i=$((${#sentence[@]}-1))
while [ "$i" -ge 0 ]; do
b=0
while [ "$b" -lt "${#sentence[$i]}" ]; do
if [ "${sentence[$i]:$b:1}" == "?" ] || \
[ "${sentence[$i]:$b:1}" == "!" ] || \
[ "${sentence[$i]:$b:1}" == "." ]; then
terminator="${sentence[$i]:$b:1}"
sentence["$i"]=$(tr -d [:punct:] <<<"${sentence[$i]}")
break
fi
((b++))
done
echo -n "$(tr [A-Z] [a-z] <<<${sentence[$i]})"
if [ "$i" -gt 0 ]; then
echo -n " "
fi
((i--))
done
if [ -n "$terminator" ]; then
echo "$terminator"
else
echo
fi
exit 0
Input:
Enter a sentence: Every living thing is a masterpiece, written by nature and edited by evolution!
Output:
evolution by edited and nature by written masterpiece, a is thing living every!
$(...)command substitution<<<here string, fortrinput${sentence##[.\!?]}- remove . ! or ? from the end of the stringtr ' ' '\n'- replaces spaces by newlines<<<$var tr ' ' '\n'ortr ' ' '\n' <<<$varis the same asecho "$var" | tr ' ' '\n'tac- seetac --helppaste -sd ' '- join lines with spaces${sentence##*[^.\!?]}- remove all characters from sentence up until . ! ?echo "$(cmd)"is justcmd), becuase it'secho "$(...)${sentence...}"