2011-11-24 292 views
2

我试图用shell脚本以表格格式打印一组值。该表有n行和4列。我试了下面这段代码。Shell脚本以表格格式打印

btfield=`grep -i -r ^"diag.* <string>" *.txt |awk '{print $5}'|cut -d+ -f 1 |sort -u` 
ipaddr='' 
i=0 
format="%10s\t%10s\t%10s \n" 
echo "| Function " "  |   IP   |" " occurences  |" 
for a in $btfield 
do 
    b=`grep -i -r ^"diag.* <string>" *.txt |grep -i $a |cut -d: -f 1|cut -d_ -f 2|cut -d't' -f 1` 
    noOcc=`grep -i -r ^"diag.* backtrace" *.txt |grep -i $a|wc -l` 
    #echo $b 
    ipaddr[i]=${b} 
    printf "$format" $a ${ipaddr[i]} $noOcc 
    i=$((i+1)) 
    #echo $i 
done 

上面这段代码根据格式说明符从各种文件中找到不同的字段并进行打印。

但我所看到的是输出的错位形式。有什么方法可以打印表格格式的值?列宽是固定的,如果单元格中的值超过宽度,它必须自行包装。

Sample output: 

|  reason   |  STB IP   |  occurences  | 
printf  142.25.1.100. 142.25.1.100. 
142.25.1.102. 142.25.1.105. 192.168.1.100. 
192.168.1.100. 192.168.1.100. 192.168.1.100. 
192.168.1.106.   9     
class_consol  142.25.1.105. 192.168.1.103. 
     2         
getChar 182.168.1.102.   1 
    maindat  142.25.1.103.   1 
_XN52getappdatafrom3EZN2232_iPjj  142.25.1.103. 142.25.1.103. 
182.168.1.106.  

回答

4

而不是使用回声,请使用printf命令。

你可以使用%S字符串或%d整数,这样的事情,

printf " %s %d", $string1 $int1 

你可以根据你的屏幕空间,通过使用%20s使用20个字符的字符串,%12d为整数。

格式控制选项也可用:

\ n:换行

\ t:制表键(水平)

符\ v:标签(垂直)

我希望这有助于

2

只要在printf中明确指出逗号是不需要的。

所有要打印的内容都应该用双引号引起来,在引用这些引号之后,你必须提到在双引号内使用的变量。

例如:

name=barack 
age=52 
printf "My name is %s \t age is %s \n" $name $age 

输出:

my name is barack  age is 52 

确切问题的答案是(假设为可变值被正确计算):

印刷标题:

printf "|\tFunction\t|\tIP\t|\toccurences\t|\n" 

印刷值:当然

printf "|\t%s\t|\t%s\t|\t%s\t|\n" $a ${ipaddr[i]} $noOcc 

数翼片(\ t)的取决于数据的长度。