Reverse of a string

Hi All,

I have a String str="Manish". I would like to reverse it.

I know the option to do this in bash is: echo "Manish" | rev

but I have seen an alternate solution somewhere, which states that:

str="Manish" echo $str | awk '{ for(i=length($0);i>=1;i--) printf("%s",substr($0,i,1)); }'

In above script I have a doubt about the $0.

when I use $0 on console then it gives output : bash, while using it in script it is showing the desired output.

Could anyone please help me in understanding the $0 work here..

Many thanks in advance.

$0 is for the entire line - when we are using it in awk. (in your case Manish)
$0 is the name of the script itself.
$0 - is the filename or command name when you are using it inside a file or command.

when you do echo $0, the echo command is executed by bash shell. So it gives the output as bash.

Special Variable Types
Unix - Special Variables

Everything inside single quotes there gets fed into awk literally. So it gives awk $0, not the first argument.

awk considers $0 to be the entire line.

You can simplify that a bit by setting FS="", which makes each field its own character:

echo "slartibartfast" | awk -v FS="" '{ for(N=NF; N>=1; N--) printf("%s", $N); }'
echo 'abcdefghijk' | sed '/\n/!G;s/\(.\)\(.*\n\)/&\2\1/;//D;s/.//'

That's beautiful in a hideous way. I was tempted to think the \n would do nothing, but apparently it's necessary. What does it do? :eek:

Famous Sed One-Liners Explained, Part I: File Spacing, Numbering and Text Conversion and Substitution - #37.

Note that this is a GNU awk extension and it's not specified by the POSIX standard.

vgersh99, can you please explain how it reverses?

thank you

--ahamed