表格式化shell脚本

时间:2016-06-08 20:52:21

标签: linux shell awk

我有一个shell脚本,它从Vserver中提取信息,这是脚本:

el01test
Virtual

Oracle Linux Server

2

7

1

2

19.16.10.111 12.1.0.1 12.1.0.11 12.1.2.11 127.0.0.1 
00:22:4F:F9:3C:D8 80:22:05:F7:FE:80:00:00:00:00:00:00:00:00:00:00:00:00:00:00 22:44:22:F4:FE:80:00:00:00:00:00:00:00:00:00:00:00:00:00:00 22:44:22:E2:FE:80:00:00:00:00:00:00:00:00:00:00:00:00:00:00 
19.16.10.1 
19.16.10.12 19.16.10.15 
el01:/export/el011->/home/glassfish/glassfish el01:/export/logs/el01vur01->/home/glassfish/logs el01:/export/home/oem12ag/age->/home/oem12ag/agent 
Kernel IP routing 
Destination Gateway Genmask Iface
0.0.0.0 192.168.181.1 0.0.0.0 bond0
169.254.0.0 0.0.0.0 255.255.0.0 bond1
17.1.0.0 0.0.0.0 255.255.0.0 bond2
17.1.0.0 0.0.0.0 255.255.0.0 bond1
19.16.0.0 0.0.0.0 255.255.252.0 bond3
19.16.10.0 0.0.0.0 255.255.252.0 bond0

我有以下输出(示例):

hostname    OS  Core_number Free_memory IP1
                                        IP2
                                        IP3

我想格式化我的信息:

txt_username.Text = Context.Request.QueryString['username'];

我一直在尝试使用awk,但我没有太多运气。谢谢你的帮助!

3 个答案:

答案 0 :(得分:2)

您可以通过将行读入数组来使用awk。然后将包含信息的行输出为所需的表格格式。

这是一个给你粗略想法的例子:

<强> script.awk

    { info[ i++ ] = $1 }
END { printf("%s\t%s\t%s\t%s\t%s\n", info[0], info[3], info[5], info[7], info[9])
      printf("\t\t\t\t\t\t\t%s\n", info[10])
      printf("\t\t\t\t\t\t\t%s\n", info[11])
    }

像这样使用:awk -f script.awk yourfile

答案 1 :(得分:0)

我终于完成了我的格式化脚本,感谢大家的帮助,最后你必须修改初始脚本,然后使用下一个代码对其进行格式化:

for q in $(ls); do awk ' NR >= 19 { route[ j++ ] = $0; next } NF==1 { info[ i++ ] = $1; next  } NR == 4 { OS= $0 } NR == 14  { A=split($0, Ip, " "); next } NR == 15 { B=split($0, Mac, " "); next } NR == 17 { C=split($0, Dns, " "); next } NR == 18 { D=split($0, Mount, " "); next } END { if (A > B) max1=A ; else max1=B; if (C > D) max2=C; else max2=D; if (max1 > max2) max=max1; else max=max2; if (max < j) max=j; for (i=0; i<=6; i++) {printf "%s\t ",info[i]} ; for (w = 0; w <= max; w = w+1)  { printf("\t\t\t\t\t\t\t%s\t%s\t%s\t%s\t%s\n",Ip[w], Mac[w], Dns[w], Mount[w], route[w]) }  } ' $q; done > Fullout

非常感谢你的帮助! 如果有人知道如何混合printf,以便能够在同一条线上打印,我将不胜感激。 我也知道代码可以优化,但我很着急,抱歉:(。 如果有人想为你的进一步脚本测试它,我在初始答案中发布了初始脚本的一个输出。 感谢

答案 2 :(得分:0)

您可以set tabstops使用tabs命令或内联ANSI代码,而不是编写多个标签。

ANSI/VT100 Terminal Control Escape Sequences

Linux tabs command

然后,使用单个\t标签编写输出代码。