There are several ways to reverse a string in Unix/Linux shell:
- Using
rev
command: Therev
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
- Using
awk
command: You can use theawk
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
- Using
sed
command: You can use thesed
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