awk reverse string

Hello,
Can anyone explain for me in this script to reverse the string?
1) the "x=x" part, how it works?

$ echo welcome | awk '{ for(i=length;i!=0;i--)x=x substr($0,i,1);}END{print x}'
$ emoclew

2) x seems to be an array at the END, but can it automatically print the whole array in awk?
Thanks a lot!
YT

"x" is not an array. x=x substr($0,i,1) means that substr($0,i,1) is appended to the variable x; x=x+something.

1 Like

I see, and I am almost there to catch it.

This reverse line by line

awk '{ for(i=length;i!=0;i--) x=(x substr($0,i,1))}{print x;x=""}'

No need to wait til END for the printing.
I did add parentheses to see what the x does x=(x substr($0,i,1))
It recreate the word by adding one and one letter in reverse order to the x

Value of x by run in loop

#0 x=""
#1 x=x+"e" x="e"
#2 x=x+"m" x="em"
#3 x=x+"o" x="emo"
etc
1 Like

If you want to reverse a string, here is the best way:

$ echo welcome | rev
emoclew
2 Likes

And I see it works fine on multiple lines to :slight_smile:

echo "toy
home" | rev
yot
emoh

If it cant be done with awk , its not worth doing it :wink:

1 Like

Thanks Hanson and Jotne!
I was aware of the rev cmd, but I was trying to catch the awk part. Thanks anyway.

Well, each tool has it's strengths and weaknesses. And look, if you don't let rev do it's job, the thing it was expressly designed for, it will get lonely. We wouldn't want that to happen, would we? :rolleyes:

Some systems don't include the rev utility. All UNIX and Linux systems provide awk. The OP never said what OS was being used.