Wednesday, December 3, 2008
Shell Scripting #0001 - Reverse a String in Shell Script
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/shvar="REVERSE_A_STRING"n=${#var}echo $nwhile [ $n -ne 0 ]doarr[$n]=`echo $var | cut -c$n`echo ${arr[$n]}n=$((n-1))done
Subscribe to:
Post Comments
(
Atom
)
1 comment :
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"
Post a Comment