Review your favorite Linux distribution.
Go Back > Forums > Linux Forums > Linux - Newbie
User Name
Linux - Newbie This Linux forum is for members that are new to Linux.
Just starting out and have a question? If it is not in the man pages or the how-to's this is the place!


  Search this Thread
Old 02-16-2010, 12:15 AM   #1
Registered: Sep 2008
Location: Mumbai, india
Distribution: ubuntu and hp-unix
Posts: 118

Rep: Reputation: 15
reversing string with space

Just check out the script...

      1 #!/bin/bash
      3 echo -n "Enter a string :: "
      4 read str
      5 echo -n "Reverse is :: "
      6 l=`expr length "$str"`
      7 while [ $l -ge 1 ]
      8 do
      9     m=`echo $str | cut -c "$l"`
     10     echo -n $m
     11     l=`expr $l - 1`
     12 done
     13 echo

It takes a script and shows it in reverse manner.

it works well for single word input like..


[user31@FEDORA ~]$ sh
Enter a string :: asit
Reverse is :: tisa

But ignores the white space if multi-word is entered...

[user31@FEDORA ~]$ sh
Enter a string :: qutub asit
Reverse is :: tisabutuq

How can I fix this ??
Old 02-16-2010, 12:26 AM   #2
Registered: Feb 2007
Posts: 55

Rep: Reputation: 17
Try this


echo -n "Enter a string :: "
read str
echo -n "Reverse is :: "
l=`expr length "$str"`
while [ $l -ge 1 ]
m=`echo $str | cut -c "$l"`
echo -n "$m" # $m in double quotes
l=`expr $l - 1`
Old 02-16-2010, 12:41 AM   #3
LQ 5k Club
Registered: Dec 2008
Location: Tamil Nadu, India
Distribution: Debian
Posts: 8,578
Blog Entries: 31

Rep: Reputation: 1208Reputation: 1208Reputation: 1208Reputation: 1208Reputation: 1208Reputation: 1208Reputation: 1208Reputation: 1208Reputation: 1208
Thumbs down

Add quotes around $m in echo -n $m

EDIT: hostmaster beat me to it


Thread Tools Search this Thread
Search this Thread:

Advanced Search

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is Off
HTML code is Off

Similar Threads
Thread Thread Starter Forum Replies Last Post
awk parse string with space? yech Programming 8 02-12-2010 01:33 AM
[SOLVED] grep a string with space vikas027 Programming 5 02-09-2010 04:22 PM
Reversing a string using only commands from the SUS (Single UNIX Specification) Willard Programming 6 11-17-2009 11:30 AM
grep string with space (2 word string) casperdaghost Linux - Newbie 7 08-24-2009 02:11 AM
PHP More than one space in a string Boffy Programming 4 05-01-2004 02:54 PM > Forums > Linux Forums > Linux - Newbie

All times are GMT -5. The time now is 07:07 PM.

Main Menu
Write for LQ is looking for people interested in writing Editorials, Articles, Reviews, and more. If you'd like to contribute content, let us know.
Main Menu
RSS1  Latest Threads
RSS1  LQ News
Twitter: @linuxquestions
Open Source Consulting | Domain Registration