Reversing a string using only commands from the SUS (Single UNIX Specification)
ProgrammingThis forum is for all programming questions.
The question does not have to be directly related to Linux and any language is fair game.
Notices
Welcome to LinuxQuestions.org, a friendly and active Linux Community.
You are currently viewing LQ as a guest. By joining our community you will have the ability to post topics, receive our newsletter, use the advanced search, subscribe to threads and access many other special features. Registration is quick, simple and absolutely free. Join our community today!
Note that registered members see fewer ads, and ContentLink is completely disabled once you log in.
If you have any problems with the registration process or your account login, please contact us. If you need to reset your password, click here.
Having a problem logging in? Please visit this page to clear all LQ-related cookies.
Get a virtual cloud desktop with the Linux distro that you want in less than five minutes with Shells! With over 10 pre-installed distros to choose from, the worry-free installation life is here! Whether you are a digital nomad or just looking for flexibility, Shells can put your Linux machine on the device that you want to use.
Exclusive for LQ members, get up to 45% off per month. Click here for more info.
Reversing a string using only commands from the SUS (Single UNIX Specification)
Greetings.
I would like to reverse a string using only the tools which are part of the Single UNIX Specification (POSIX). The list of UNIX utilities in that specification can be seen on Wikipedia:
Both this script, and my script, will reverse lines at a time, and remove line breaks. For completeness and elegance, it would be nice if the script would just consider the entire input stream as a single token, and reverse it, instead of treating linebreaks in a special manner.
If I remember correctly, it should be possible to re-define how a stream is tokenized. I cannot remember how, though.
A challenge: Write the shortest SUS-compliant program which reverses a string.
FILE_LINE_COUNT=0
LINE=
IFS=
while read LINE ; do
# add the curent line to the line counter
(( FILE_LINE_COUNT++ ))
OUTPUT_STRING=
STRING=$LINE
while [[ "$STRING" != "" ]] ; do
OUTPUT_STRING=${STRING:0:1}$OUTPUT_STRING
STRING=${STRING:1}
done
echo $OUTPUT_STRING
done <"$1"
Actually this uses bash, but if that particular construct doesn't work i think it can still be done with just the shell using another construct.
That code is part of a fuller file which constitutes a pretty complete implementaion of rev using pure bash.
LinuxQuestions.org is looking for people interested in writing
Editorials, Articles, Reviews, and more. If you'd like to contribute
content, let us know.