An Entrepreneur, Coach, IT Consultant, Strategic Adviser, and a Traveler craving to explore and contribute to forming a better society.

Wednesday, December 3, 2008

Shell Scripting #0001 - Reverse a String in Shell Script

1 comment :
Keywords: Shell Script, Linux, Reverse a String, Scripting

Shell Scripting #0001 - Reverse a String in Shell Script:

Problem:
How to reverse a string in Shell Script?

Example Usage:
Let us assume that you have a Date Format in YYYYMMDD in a text file and you have to perform a reverse string operation to make it DDMMYYYY.
Note: I had a problem specific to my project and the above example is depicted to keep the problem simple. So that, one will understand what to do and how to use.

Solution:
Following code snippet will help  you reversing a string in Shell:-

#/bin/sh

var="REVERSE_A_STRING"
n=${#var}
echo $n

while [ $n -ne 0 ]
do
arr[$n]=`echo $var | cut -c$n`
echo ${arr[$n]}
n=$((n-1))
done

1 comment :

sridip said...

Below is a variant of your script (without using array)

#!/usr/bin/ksh

echo "Please enter a string: "|tr -d '\n'
read str
echo "The String you entered is: $str"

echo $str|tr -d '\n'|wc -c|read len
echo $len

var=''

for i in {1..$len}; do

echo $str|cut -c $(($len-$i+1))|read char
var=$var$char
done

echo "The Reverse of the input string is: $var"