bash Unix shell 脚本可以在没有 rev 的情况下反转字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19646609/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 08:26:14  来源:igfitidea点击:

Unix shell scripting to reverse a string without rev

bashshellunix

提问by ari

I want to write a shell script that accepts a string as a command line argument and prints out what is entered in the reverse order with out using the rev command but rather reversing the letters one by one. how would I do that? so like if Flower is entered it will print out rewolF

我想编写一个 shell 脚本,它接受一个字符串作为命令行参数,并打印出以相反顺序输入的内容,而不使用 rev 命令,而是一个一个地反转字母。我该怎么做?所以就像如果输入 Flower 它将打印出 rewolF

Thanks

谢谢

回答by Gilles Quenot

A good subject for bashparameter expansion:

bash参数扩展的一个很好的主题:

#!/bin/bash

for ((i=${#1}; i>=0; i--)); do printf "${1:$i:1}"; done; echo

Example :

例子 :

./script.sh foobar 

Output :

输出 :

raboof

回答by michael501

s1='Flower'
a1=($(echo $s1|fold -w1 ))
for (( i=${#a1[@]}-1;i>=0;i--));do echo "$i=>${a1[i]}"; done
5=>r
4=>e
3=>w
2=>o
1=>l
0=>F