2012-12-04 31 views
0

如何将“ps -ef”的输出分割为“行输出”。我遇到的一个问题是如何在字符串标记过程中将“gpm -m/dev/input/mice -t exps2”作为单个项目处理。如何将“ps -ef”的输出分割为“行输出”

如果 'PS -ef' 的输出是这样的:

root  3410  1 0 Jun17 ?  00:00:00 gpm -m /dev/input/mice -t exps2 
root  3424  1 0 Jun17 ?  00:00:00 crond 
root  3488  1 0 Jun17 ?  00:00:00 /usr/sbin/atd 

然后,我怎么能漂亮打印出来,所以它看起来像:

1: 
root 
3410 
00:00:00 
gpm -m /dev/input/mice -t exps2 

2: 
root 
3424 
00:00:00 
crond 

3: 
root 
3488 
00:00:00 
/usr/sbin/atd 
+0

whathaveyoutried.com?祝你好运。 – shellter

回答

2

这里有一种方法:

let i=0 
while read line; do 
    read user pid _ _ _ _ time command <<<"$line" 
    if [ "$user" != UID ]; then # skip header line 
    printf "%s\n" $((++i)): "$user" "$pid" "$time" "$command" "" 
    fi 
done < <(ps -ef) 

您也可以与read -a直接读取线到字段的数组中的首位,但随后命令派上作为多个元素,并且将它重新组合成单​​个单词还有点多。

+0

这个答案令人难以置信。我永远不会想到这一点,我开悟了。谢谢。 – djangofan

1

使用下面的shell代码片段

OIFS=$IFS 
IFS=$'\n' 
i=0 
for line in `ps -ef`; do 
    echo "$i:" 
    echo $line | cut -d' ' -f1 
    echo $line | cut -d' ' -f2 
    echo $line | cut -d' ' -f7 
    echo $line | cut -d' ' -f8- 
    ((i++)) 
done 
IFS=$OIFS 
0

以下是一种使用方法awk

ps -ef | awk -v OFS="\n" '{ for (i=8;i<=NF;i++) line = (line ? line FS : "") $i; print NR ":", $1, $2, $7, line, ""; line = "" }' 

结果:

1: 
root 
3410 
00:00:00 
gpm -m /dev/input/mice -t exps2 

2: 
root 
3424 
00:00:00 
crond 

3: 
root 
3488 
00:00:00 
/usr/sbin/atd 
+0

很好的答案,但我喜欢Mark Reed如何在没有任何其他工具的情况下编写脚本,除了'ps'。 – djangofan

+0

@djangofan:和shell ... – Steve