如何将变量重定向到文本文件然后按字母顺序排序

时间:2014-11-18 05:56:14

标签: bash alphabetical

我的脚本是一次要求输入1大写,并且需要显示0无效输入结束并显示第一个有效的大写字母。

#! /bin/sh
count=0

until [[ $n =~ 0 ]]; do
    echo Inputs:
    read n
    if [[ $n =~ ^[A-Z]$ ]]; then
        count=`expr $count + 1`
        echo $n | sort > out.txt
    fi
done

echo The total number of valid input letters:
echo $count
echo " "
echo The first valid input:
head -n 1 /filepath/out.txt

输出:

Inputs:
B
Inputs:
A
Inputs:
C
Inputs:
0

The total number of valid input letters:
3

The first valid input:
C

问题:应该导致A. 任何帮助将不胜感激。

3 个答案:

答案 0 :(得分:0)

这一行:

echo $n | sort > out.txt

总是只用最新的输入来压缩文件out.txt。也许你应该使用:

cp /dev/null out.txt   # Before the loop

echo $n | sort -o out.txt out.txt -

cp命令会创建一个空文件。 sort命令读取现有文件out.txt及其标准输入(新行),对结果进行排序并将其写出out.txt

这对于短输入是可以的;如果需要扩展到数千行,效率不高。

此外,在Bash中,您不需要使用expr进行算术运算:

((count++))

答案 1 :(得分:0)

使用以下代码。

#! /bin/sh
count=0

>out.txt
until [[ $n =~ 0 ]]; do
    read -p 'Inputs: ' n
    if [[ $n =~ ^[A-Z]$ ]]; then
        count=`expr $count + 1`
        echo $n  >> out.txt
    fi
done

echo The total number of valid input letters:
echo $count
echo " "
echo The first valid input:
sort out.txt |head -n 1

输出:

Inputs: B
Inputs: A
Inputs: C
Inputs: 0
The total number of valid input letters:
3

The first valid input:
A

答案 2 :(得分:0)

由于您只想要最小的(按字母顺序排列)有效输入,因此您不需要排序。这里有一个替代答案,不使用排序,只保留最小的有效输入:

#!/bin/sh

count=0

until [[ $n =~ 0 ]]; do
    echo Inputs:
    read n
    if [[ $n =~ ^[A-Z]$ ]]; then
        ((count++))
        if [ -z $first ] || [ `expr $n \< $first` -eq 1 ]; then
            first=$n
        fi
    fi
done

echo The total number of valid input letters:
echo $count
echo " "
echo The first valid input:
echo $first