How to reverse a string in ksh

允我心安 提交于 2019-12-07 18:55:13

问题


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

回答1:


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



回答2:


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



回答3:


You could use cut, paste and rev together, just change printf to cat file.txt:

paste -d' ' <(printf "%s data\n" {1..100} | cut -d' ' -f1) <(printf "%s data\n" {1..100} | cut -d' ' -f2 |rev)

Or rev alone if, it's not a numbered file as clarified by the OP.



来源:https://stackoverflow.com/questions/36745088/how-to-reverse-a-string-in-ksh

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!