How to redirect variable into text file then sort alphabetical

187 views Asked by At

My script is to ask for input 1 upper case at a time and end with 0 invalid input will need to be displayed and display the first valid upper letter.

#! /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

Output:

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

The total number of valid input letters:
3

The first valid input:
C

Question: It should result in A. Any help will be appreciated.

3

There are 3 answers

0
Robin Hsu On

Since you want only the smallest (in alphabet order) valid input, you don't need sort. Here's an alternative answer not using sort but just keep the smallest valid input:

#!/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
0
Jonathan Leffler On

This line:

echo $n | sort > out.txt

always zaps the file out.txt with just the latest input. Maybe you should use:

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

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

The cp command creates an empty file. The sort command reads the existing file out.txt and its standard input (the new line), sorts the result and writes it out over out.txt.

This is OK for short inputs; it isn't very efficient if it needs to scale to thousands of lines.

Also, in Bash, you don't need to use expr for arithmetic:

((count++))
0
Sriharsha Kalluru On

Use the following code.

#! /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

Output:

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

The first valid input:
A