以列形式显示输出

以列形式显示输出

我编写了一个 shell 脚本,使用case.代码是:

echo "Press 1 for user name, 2 for terminal name, 3 for login date and 4 for time"
read ch
case $ch in
1)
echo `who | cut -c1-8 | cut -d" " -f1`
;;
2)
echo `who | cut -c9-16 | column`
;;
3)
echo `who | cut -c22-32 | sort`
;;
4)
echo `who | cut -c34-39`
;;
esac

当我运行此脚本时,输出位于一行中,我希望它以柱状格式显示(即在单列中跨多行列出)。我已经尝试过cutcolumnsort命令,但仍然没有喘息的机会。输出是:

Press 1 for user name, 2 for terminal name, 3 for login date and 4 for time
1
bioinfo class class class class class class class class class class
[class@bio ~]$

答案1

我会使用awk而不是cut为此,例如:

#!/bin/bash

echo "Press 1 for user name, 2 for terminal name, 3 for login date and 4 for time"
read ch
case $ch in
    1)  
    who | awk '{ print $1 }'
    ;;  
    2)  
    who | awk '{ print $2 }'
    ;;  
    3)  
    who | awk '{ print $3 " " $4 }'
    ;;  
    4)  
    who | awk '{ print $5 }'
    ;;  
    *)  
    echo "Wrong input"
esac

执行样本:

./whoList.sh 
Press 1 for user name, 2 for terminal name, 3 for login date and 4 for time
2
console
ttys000
ttys001

./whoList.sh 
Press 1 for user name, 2 for terminal name, 3 for login date and 4 for time
3
Oct 3
Oct 3
Oct 3

./whoList.sh 
Press 1 for user name, 2 for terminal name, 3 for login date and 4 for time
1
maulinglawns
maulinglawns
maulinglawns

./whoList.sh 
Press 1 for user name, 2 for terminal name, 3 for login date and 4 for time
4
09:01
09:44
11:01

./whoList.sh
Press 1 for user name, 2 for terminal name, 3 for login date and 4 for time
7
Wrong input

正如您所看到的,输出全部合二为一柱子,不在一条线上。

编辑:在 OS X 10.11.6 下测试

bash --version GNU bash, version 3.2.57(1)-release (x86_64-apple-darwin15)

相关内容