How to reverse a string

In this article, we will see different methods with which we can reverse a string.  Let's just use the string " linux and life" as the sample.

1. Use rev

This is the easiest method. The rev command is to reverse. The command will be very simple as following:
 echo linux and life | rev  

2. Use awk

With the substring function, we can use awk to reverse the string. We start from the last character of the string and keep printing a character till the first one is reached:
 echo linux and life | awk '{ for(i=length;i!=0;i--)x=x substr($0,i,1);}END{print x}'  

The length command gives the length of the argument passed to it. With no argument, length gives the length of the current line which is $0. The substr command in awk extracts one character at a time and is appended to the resulted variable x which is printed at the end using the END label.

3. Use sed

We can use 2 sed commands to do the task.
 echo linux and life | sed 's/./&\n/g' | tac | sed -e :a -e 'N;s/\n//g;ta'  

In the command above, the first sed reads a character(.) and appends a newline(\n) character behind every matched character(&). Then the tac command reverses the contents of a file or the standard input. And the second sed command now joins all the lines together.

4. Use perl

Perl has the reverse function that we can use to do the task. The reverse function reverses all the elements present in a list including a string:
 echo linux and life | perl -ne 'chomp;print scalar reverse;'  

The chomp command here is to remove the newline character in the string.
linux tips and tricks