Tuesday, May 22, 2012

Different ways to reverse a string in Linux



 In this article, we will see the different ways in which we can reverse a string in Linux. Let us take a string "welcome" and try to reverse this string in different ways:

1. The Linux rev command is used to reverse the lines in a file. This command can take standard input as well as shown below.
$ echo welcome | rev
emoclew
Note: The rev command is not present in all flavors of Unix.

2. awk, using the substring function, can reverse a string:
$ echo welcome | awk '{ for(i=length;i!=0;i--)x=x substr($0,i,1);}END{print x}'
emoclew
    This logic is the common logic used in any programming language to reverse a string: Start from the last position of the string and keep printing a character till the first position is reached.  We loop on the string starting from the last position and moving towards the beginning. 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 resultant variable x which is printed at the end using the END label. 

3. Using sed. 2 sed commands are used here.
$ echo welcome | sed 's/./&\n/g' | tac | sed -e :a -e 'N;s/\n//g;ta'
emoclew
   To understand this command properly, break it up at every pipe and observe  the output. The first sed reads a character(.) and appends a newline(\n) character behind every matched character(&). tac command reverses the contents of a file or the standard input. The second sed command now joins all the lines together.

Note: The tac command is not present in all the Unix flavors.

4. Perl solution using the inbuilt perl function reverse.
$ echo welcome | perl -ne 'chomp;print scalar reverse;'
emoclew
  reverse function reverses all the elements present in a list. In scalar context as used here, it reverses a string as well. The chomp command is used to remove the newline character in the string.

5. The traditional way of using a shell script:
#!/bin/bash
x="welcome"
len=`echo ${#x}`
while [ $len -ne 0 ]
do
        y=$y`echo $x | cut -c $len`
        ((len--))
done
echo $y
    This script is self explanatory if you know shell scripting. The length of the string is saved in variable len. A while loop is run on the variable len until it becomes zero. Using the cut command, the character  pointed by the position len is appended to the result, and the len variable is decremented. At the end of the loop, the variable y contains the reversed string.

  Note:If you do not have bash shell and if your ksh is older version, just replace the ((len--) with "let len=len-1".  ((len--) syntax works well in the latest ksh version(ksh93).

No comments:

Post a Comment