To reverse a string

Hi All,

I would like to know , how to reverse a given string

example :

Hi how are you

Required Output:

you are how Hi

Thanks

try using awk , for and NF ....:slight_smile:

This thread might help you:
http://www.unix.com/shell-programming-scripting/199009-how-reverse-sentence-linux-bash-cshell.html
The last post in this thread should be interesting.

And, for this particular example, try:

perl -e '$str="Hi how are you";
while($str =~ /.*(\b\w+\b)/) { print $1," ";$str =~ s/(.*)(\b\w+\b)/\1/} print "\n"'

producing

you are how Hi

Thank you , it s working..

awk '{ for (i=NF;i>=1;i--) { if(s!= ""){s=s" "$i}else{ s=$i  }} {print s;s=""}}' file

but i dint understand this part
if(s!= ""){s=s" "$i}else{ s=$i }} {print s;s=""}}... can you pls explain ?

awk perform operations line by line.
At first line we have no defined s yet. so just we check is s present or not.

if(s!= "")   # Check here s present or not if s presents the append next character to it. here you also can use if(s)
{s=s" "$i} # Here we do append part. All the words are appended in reverse manner.
else{ s=$i  }} # here we initialize s. s=$NF
{print s;s=""}} # and at the lat after end of for loop we print final s(which is reversed output of the input line) and make s="" ready to to next line

Hope this helps you:)

echo "you are how Hi" | awk 'BEGIN{RS=" ";ORS=" "}{arr[NR-1]=$1;num++}END{for (i=num-1;i>=0;i--)print arr}'
1 Like

what is "s" actually ?

s is just a variable:).

You can use p,q,r and so on instead of s. whichever you like...:smiley:

We are just using s for storing the output.

1 Like