Shell脚本以表格格式打印

时间:2011-11-24 05:13:35

标签: shell

我正在尝试使用shell脚本以表格格式打印一组值。该表有n行和4列。我尝试了以下一段代码。

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.    

2 个答案:

答案 0 :(得分:5)

使用printf命令,而不是使用echo。

您可以将%s用于字符串,将%d用于整数,类似这样,

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

您可以根据屏幕使用%20s空格,字符串使用20个字符,整数使用%12d

格式控制选项也可用:

\ n:换行符

\ t:标签(水平)

\ v:tab(垂直)

我希望这会有所帮助

答案 1 :(得分: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)取决于您的数据长度。

相关问题