我正在尝试交换用户输入的字符串[复制]

问题描述 投票:-3回答:2

这个问题在这里已有答案:

我正在尝试编写一个bash脚本来交换用户输入的单词。

例如:hello stack overflow

输出:overflow stack hello

用户可以输入任意数量的单词。

bash
2个回答
0
投票

试试这个:

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 

0
投票

看一下下面的文章,解释在bash中使用“read”:

http://landoflinux.com/linux_bash_scripting_read.html

如果你提前知道要切换的单词数,一个简单的解决方案可能是这样的。每个单词都分配给read命令中指定的变量:

#!/bin/bash
echo "Enter two words: "
read one two
echo "first word: $one"
echo "second word: $two"

如果您需要反转一个字符串中的单词列表,可以查看以下答案:

How to reverse a list of words in a shell string?

© www.soinside.com 2019 - 2024. All rights reserved.