【问题标题】:I am trying to swap the string entered by user [duplicate]我正在尝试交换用户输入的字符串 [重复]
【发布时间】:2019-04-13 11:43:15
【问题描述】:

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

例如:hello stack overflow

输出:overflow stack hello

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

【问题讨论】:

  • 您有问题吗?如果是“我该怎么做?”,它不适合这个网站。

标签: bash


【解决方案1】:

试试这个:

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 

【讨论】:

    【解决方案2】:

    请看以下解释 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"
    

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-03-15
      • 1970-01-01
      • 1970-01-01
      • 2021-10-04
      • 1970-01-01
      • 2013-11-22
      • 2016-04-10
      • 1970-01-01
      相关资源
      最近更新 更多