0

The script will read the contents of a user-input file and count the number of employees with a specific job. Ex file line:

Sophia Lewis, 542467, Accountant 

The script I have so far is:

if [ -s $1 ]
then

cat $1 | tr -s ' ' | cut -d' ' -f4- | sort | uniq -c

else
        echo "ERROR: file '$1' does not exist."

fi

Output:

4 Sales 
2 Accountant 
1 CEO 

But I want the output to appear as:

There are 4 ‘Sales’ employees. 
There are 2 ‘Accountant’ employees. 
There is 1 ‘CEO’ employee. 
There are a total of 7 employees in the company

Should I take out the cat and put in echo statements so I can customize each line? And is there a way for it to know if it should be "is/are" x employees?

  • Yes, you will need to rewrite it and no, the only way for it to know is for you to code it. – terdon Apr 21 '14 at 16:38
3

If your shell is bash version 4:

declare -i total=0
declare -A type
if [ -s "$1" ]; then
    while IFS=, read name id job; do
        [[ $job =~ ^[[:space:]]*(.+)[[:space:]]*$ ]] &&
        (( type["${BASH_REMATCH[1]}"]++, total++ ))
    done < "$1"
    for job in "${!type[@]}"; do
        printf "There are %d '%s' employees.\n" ${type["$job"]} "$job"
    done
    echo "There are a total of $total employees in the company"
else
    echo "ERROR: file '$1' does not exist or has zero size."
fi

Or use awk:

awk -F' *, *' '
    { type[$3]++; total++ } 
    END {
        for (job in type) 
            printf "There are %d '\''%s'\'' employees.\n", type[job], job
        print "There are a total of", total, "employees in the company"
    }
' "$1"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.