在表格格式中打印Shell脚本

5
我正在尝试使用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个回答

8

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

您可以使用%s表示字符串,使用%d表示整数:

printf "%20s %8d %s\n" "$string1" $int1 "$unbounded_string"

您可以根据您的屏幕使用空格,通过使用%20s来使用20个字符的字符串,%8d用于整数。
还提供格式控制选项: \n:换行 \t:制表符(水平) \v:制表符(垂直)

5

请注意,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)的数量取决于您的数据长度。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接