Shell脚本以表格格式打印

Kni*_*t71 4 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
Run Code Online (Sandbox Code Playgroud)

上面的代码根据格式说明符从各种文件和打印中查找不同的字段.

但我所看到的是输出的错位形式.有没有办法以表格格式打印值?列宽是固定的,如果单元格中的值超过宽度,则必须自行换行.

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.    
Run Code Online (Sandbox Code Playgroud)

Kir*_*ran 5

使用printf命令而不是使用echo .

您可以将%s用于字符串,将%d用于整数,如下所示,

printf " %s %d", $string1 $int1
Run Code Online (Sandbox Code Playgroud)

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

格式控制选项也可用:

\n:换行

\ t:标签(水平)

\ v:标签(垂直)

我希望这有帮助


pra*_*ntk 5

只是明确说明 printf 中不需要逗号。

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

例如:

name=barack
age=52
printf "My name is %s \t age is %s \n" $name $age
Run Code Online (Sandbox Code Playgroud)

输出:

my name is barack       age is 52
Run Code Online (Sandbox Code Playgroud)

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

印刷标题:

printf "|\tFunction\t|\tIP\t|\toccurences\t|\n" 
Run Code Online (Sandbox Code Playgroud)

印刷值:

printf "|\t%s\t|\t%s\t|\t%s\t|\n" $a  ${ipaddr[i]} $noOcc 
Run Code Online (Sandbox Code Playgroud)

当然,制表符 (\t) 的数量取决于您的数据长度。