Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to reverse a string in ksh

please help me with this problem, i have an array witch includes 1000 lines with number which are treated as strings and i want for all of them to reverse them one by one, my problem is how to reverse them because i have to use ksh or else with bash or something it would be so easy..... what i have now is this, but rev="$rev${copy:$y:1}" doesnt work in ksh.

i=0
while [[ $i -lt 999 ]]
do  
    rev=""
    var=${xnumbers[$i]}
    copy=${var}
    len=${#copy}
    y=$(expr $len - 1)
    while [[ $y -ge 0 ]]
    do  
        rev="$rev${copy:$y:1}"
        echo "y = " $y
        y=$(expr $y - 1)
    done

    echo "i = " $i
    echo "rev = " $rev
    #xnumbers[$i]=$(expr $xnumbers[$i] "|" $rev)
    echo "xum = " ${xnumbers[$i]}
    echo "##############################################"
    i=$(expr $i + 1)
done
like image 215
Sir. Hedgehog Avatar asked Jan 21 '26 08:01

Sir. Hedgehog


2 Answers

I am not sure why we cannot use built in rev function.

$ echo 798|rev
897

You can also try:

$ echo 798 | awk '{ for(i=length;i!=0;i--)x=x substr($0,i,1);}END{print x}'
897
like image 85
The Roy Avatar answered Jan 23 '26 04:01

The Roy


If, you can print the contents of the array to a file, you can then process the file with this awk oneliner.

awk '{s1=split($0,A,""); line=""; for (i=s1;i>0;i--) line=line A[i];print line}' file

Check this!!

other_var=`echo ${xnumbers[$i]} | awk '{s1=split($0,A,""); line=""; for (i=s1;i>0;i--) line=line A[i];print line}'`

I have tested this on Ubuntu with ksh, same results:

number="789"
other_var=`echo $number | awk '{s1=split($0,A,""); line=""; for (i=s1;i>0;i--) line=line A[i];print line}'`
echo $other_var
987
like image 39
Firefly Avatar answered Jan 23 '26 04:01

Firefly



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!