Bash-修改自定义输出语句的代码

Bash-修改自定义输出语句的代码

该脚本将读取用户输入文件的内容并计算从事特定工作的员工人数。前文件行:

Sophia Lewis, 542467, Accountant 

到目前为止我的脚本是:

if [ -s $1 ]
then

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

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

fi

输出:

4 Sales 
2 Accountant 
1 CEO 

但我希望输出显示为:

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

我应该取出猫并放入 echo 语句以便我可以自定义每一行吗?有没有办法让它知道它是否应该是“是/是”x 员工?

答案1

如果您的 shell 是 bash 版本 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

或者使用 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"

相关内容