reverse the order of characters in a string

Viewed 103875

In string "12345", out string "54321". Preferably without third party tools and regex.

13 Answers

Some simple methods of reversing a string

echo '!!!esreveR si sihT' | grep -o . | tac | tr -d '\n' ; echo

echo '!!!esreveR si sihT' | fold -w 1 | tac | tr -d '\n' ; echo

Convert to hex values then reverse

echo '!!!esreveR si sihT' | xxd -p | grep -o .. | tac | xxd -r -p ; echo

echo '!!!esreveR si sihT' | xxd -p | fold -w 2 | tac | xxd -r -p ; echo

Nobody appears to have posted a sed solution, so here's one that works in non-GNU sed (so I wouldn't consider it "3rd party"). It does capture single characters using the regex ., but that's the only regex.

In two stages:

$ echo 123456 | sed $'s/./&\\\n/g' | sed -ne $'x;H;${x;s/\\n//g;p;}'
654321

This uses bash format substitution to include newlines in the scripts (since the question is tagged ). It works by first separating the input string into one line per character, and then by inserting each character into the beginning of the hold buffer.

  • x swaps the hold space and the pattern space, and
  • H H appends the (current) pattern space to the hold space.

So for every character, we place that character into the hold space, then append the old hold space to it, thus reversing the input. The final command removes the newlines in order to reconstruct the original string.

This should work for any single string, but it will concatenate multi-line input into a single output string.

Here is another simpler awk solution:

awk 'BEGIN{FS=""} {for (i=NF; i>0; i--) s=s $i; print s}' <<< '123456'

654321

read word

reve=`echo "$word" | awk '{for(i=length($0); i>0;i--) printf (substr($0,i,1));}'`
echo  "$reve"
Related