【发布时间】:2019-04-13 11:43:15
【问题描述】:
我正在尝试编写一个 bash 脚本来交换用户输入的单词。
例如:hello stack overflow
输出:overflow stack hello
用户可以输入任意数量的单词。
【问题讨论】:
-
您有问题吗?如果是“我该怎么做?”,它不适合这个网站。
标签: bash
我正在尝试编写一个 bash 脚本来交换用户输入的单词。
例如:hello stack overflow
输出:overflow stack hello
用户可以输入任意数量的单词。
【问题讨论】:
标签: bash
试试这个:
read -ra line # read into array
i=${#line[@]} # determine length of array
for i in $(seq $((i-1)) -1 0); do # loop in reverse order
echo -n "${line[i]} " # echo entry at i-position without linefeed
done
echo # linefeed
输入
this is a test
输出
test a is this
【讨论】:
请看以下解释 bash 中“read”使用的文章:
http://landoflinux.com/linux_bash_scripting_read.html
如果您提前知道要转换的字数,一个简单的解决方案可能是这样的。每个单词都分配给您的读取命令中指定的变量:
#!/bin/bash
echo "Enter two words: "
read one two
echo "first word: $one"
echo "second word: $two"
如果你需要反转一个字符串中的单词列表,你可以看看这个答案:
【讨论】: