【问题标题】:Sorting user input by alphabetical order in UNIX/Bash script在 UNIX/Bash 脚本中按字母顺序对用户输入进行排序
【发布时间】:2021-12-16 13:56:53
【问题描述】:

我在 Unix 中创建一个程序,我从用户那里获取三个输入(更具体地说,三个名字),我需要按字母顺序输出它们。我有一个嵌套条件,但它不起作用,我尝试了很多变化,但我不确定我错过了什么......这是我到目前为止所拥有的:

#!/bin/bash

echo -n "Enter a friend's name: "
read n1

echo -n "Enter another friend's name: "
read n2

echo -n "Enter a third friend's name: "
read n3


if [[ $n1 < $n2 ]]
then
    if [[ $n3 < $n1 ]]
    then
        echo $n3 $n1 $n2
    elif [[ $n3 < $n2 ]]
    then
        echo $n1 $n3 $n2
    else
        echo $n1 $n2 $n3
    fi
fi

if [[ $n1 < $n3 ]]
then
    if [[ $n2 < $n1 ]]
    then
        echo $n2 $n1 $n3
    elif [[ $n3 < $n2 ]]
    then
        echo $n3 $n2 $n1
    else
        echo $n2 $n3 $n1
    fi
fi

我相信我的问题来自这样一个事实,即当我输入一个名字时,例如,一开始是 Zoe,它会变得一团糟。

谢谢

【问题讨论】:

  • 排序并转换回单行:printf "%s\n" "$n1" "$n2" "$n3" | sort | tr '\n' ' '

标签: bash unix conditional-statements


【解决方案1】:

正如人们在 cmets 中指出的那样,使用 sort 可能是更好的方法;但是让我看看当前代码有什么问题。

基本问题是你有两个独立的if 块:

if [[ $n1 < $n2 ]]
    ...

if [[ $n1 < $n3 ]]
    ...

因此,如果两个条件都不成立(即如果$n1 出现在$n2$n3 之后,即顺序是CBA 或CAB),那么两个if 块都会被跳过并且不会打印任何内容。

另一个问题是,如果两个条件都为真(即如果$n1之前同时出现$n2$n3,即顺序是ABC或ACB),那么两个if 块都将运行。所以它会打印两次答案(除了第二次实际上会出错)。

解决方案是将您的主要条件设置为单个if ... elif ... else ...,以便恰好有一个块将执行。您还需要仔细跟踪哪些可能的条件导致代码的哪些部分,以便在正确的位置处理每个条件(即每个可能的名称顺序)。像这样的:

if [[ $n1 < $n2 ]]
    ...code with more ifs to handle ABC, ACB, and BCA

elif [[ $n1 < $n3 ]]
    # Note: to reach this point, [[ $n1 < $n2 ]] must be false
    # AND [[ $n1 < $n3 ]] must be true
    ...code that handles BAC ('cause that's the only case that gets here)

elif [[ $n2 < $n3 ]]
    # Note: to reach this point, [[ $n1 < $n2 ]] and [[ $n1 < $n3 ]]
    # must both be false, AND [[ $n2 < $n3 ]] must be true
    ...code that handles CAB

else
    # Note: to reach this point, ALL of the previous tests
    # must be false
    ...code that handles CBA

您还可以以更对称的方式组织它:

if [[ $n1 < $n2 ]]
    ...code with more ifs to handle ABC, ACB, and BCA

else
    ...code with more ifs to handle BAC, CAB, and CBA

【讨论】:

    猜你喜欢
    • 2019-12-29
    • 2019-11-22
    • 1970-01-01
    • 2011-08-29
    • 2013-08-24
    • 2013-11-30
    • 2017-05-22
    • 1970-01-01
    相关资源
    最近更新 更多