How To Reverse a String In Unix / Linux Shell?

There are several ways to reverse a string in Unix/Linux shell:

  1. Using rev command: The rev command is a utility that reverses the order of characters in a text file or standard input. To reverse a string, you can use the following syntax:
echo "string_to_reverse" | rev

For example:

echo "hello world" | rev

This will output:

dlrow olleh
  1. Using awk command: You can use the awk command to reverse a string by reading each character in reverse order and concatenating them. The following syntax can be used:
echo "string_to_reverse" | awk '{ for (i=length; i>0; i--) printf("%c", substr($0, i, 1)); print "" }'

For example:

echo "hello world" | awk '{ for (i=length; i>0; i--) printf("%c", substr($0, i, 1)); print "" }'

This will output:

dlrow olleh
  1. Using sed command: You can use the sed command to reverse a string by matching each character and replacing it with its reverse. The following syntax can be used:
echo "string_to_reverse" | sed -n '1h;1!H;${g;s/.//g;s/\(.\)/\1\n/g;p}' | tac

For example:

echo "hello world" | sed -n '1h;1!H;${g;s/.//g;s/\(.\)/\1\n/g;p}' | tac

This will output:

dlrow olleh

Leave a Comment