结果:

结果:

我有两个文件:

文件1:是交换机中接口数量的列表:

1/1
1/2
1/3
1/4
1/5
.
.

文件2:包含VLAN-ID, VLAN-NAME, Interfaces属于该 VLAN

1,"vlan-wifi",1/1,1/7,1/8
2,"vlan-admin",1/3,1/5,1/6
3," " ,3/3,1/3

我正在尝试使用这些文件创建一个表,例如:

                    |   interface Switch
VLAN-ID | VLAN-NAME |1/1|1/2|1/3|1/4|1/5|1/6|1/7|1/8|1/9|1/10|...|3/3
    1   |  vlan-wifi| * |   |   |   |   |   | * | * |   |    |   |
    2   | vlan-admin|   |   | * |   | * | * |   |   |   |    |   |
    3   |           |   |   | * |   |   |   |   |   |   |    |   | *

我怎样才能实现这个目标?

答案1

您不想使用 shell 循环来处理文本。在这里,这是一个典型的工作awk

awk -F '"? *, *"?' '
   !ports_processed {
      port[++ports] = $0; width[ports] = length; next
   }
   FNR==1 {
     printf "                    |   interface Switch\nVLAN-ID | VLAN-NAME "
     for (i = 1; i <= ports; i++) printf "|%s", port[i]
     print ""
   }
   {
     printf "%6d  |%11s", $1, $2
     split("", member)
     for (i = 3; i <= NF; i++) member[$i]
     for (i = 1; i <= ports; i++)
       printf "| %*s", 1 - width[i], (port[i] in member ? "*" : " ")
     print ""
   }' file-1 ports_processed=1 file-2

(这里假设 VLAN 名称不包含逗号、双引号或换行符(如果可能发生这些情况,我们需要知道它们是如何编码的))

要回答本主题中的问题,对于具有多维数组支持的 shell,请查看ksh93。它还具有 csv 解析和写入功能。

答案2

如果您不想被字段宽度所困扰,您可以使用tbl,实用程序:nroff

perl -F'\"?,\"?' -lane '
   BEGIN {
      chomp(@A = qx(sort -t/ -k1,1n -k2,2n < $ARGV[0]));
      shift;

      # prepare table for the tbl utiity
      print q/.TS/;
      print join(",", qw/allbox center/, qq/tab(\t);/)       ;
      print join($",  qw/c s c/,         qw/s/ x $#A)        ;
      print join($",  qw/c r/,           qw/c/ x  @A), qw/./ ;
      print join("\t", $,, q/interface switch/);
      print join("\t", qw/VLAN-ID VLAN-NAME/, @A);
   }

    print
join("\t", @F[0,1], map { my $e = $_; (0 < grep { $e eq $_ } @F[2..$#F]) ? q[*] : q[] } @A);

   END { print q/.TE/; }
' file-1 file-2 | tbl - | nroff -Tascii -ms | sed -n '/./!d;$!N;s/.*\n.\(.*\)./\1/p'

结果:

                     |                         interface switch                         
VLAN-ID |  VLAN-NAME | 1/1 | 1/2 | 1/3 | 1/4 | 1/5 | 1/6 | 1/7 | 1/8 | 1/9 | 1/10 | 3/3 
   1    |  vlan-wifi |  *  |     |     |     |     |     |  *  |  *  |     |      |     
   2    | vlan-admin |     |     |  *  |     |  *  |  *  |     |     |     |      |     
   3    |            |     |     |  *  |     |     |     |     |     |     |      |  *  

答案3

这是使用 Python 实现此目的的一种方法。注意文件1从你的问题来看似乎不需要,所以这个脚本只需要一个参数:

代码:

import sys

filename = sys.argv[1]
vids = {}
intfs = set()
with open(filename, 'rU') as f:
    for line in f:
        vid, vname, vintf = line.strip().split(',', 2)
        vintf = vintf.split(',')
        vids[int(vid)] = (vname.strip('"').strip(), vintf)
        intfs |= set(vintf)

intfs = [(i, len(i)) for i in
         sorted(intfs, key=lambda x: tuple(int(y) for y in x.split('/')))]

max_name_len = max(len(i[0]) for i in vids.values()) + 1

line = ('VLAN-ID |%%%ds' % max_name_len) % (
    'VLAN-NAME' + ' ' * ((max_name_len - 9) / 2))
for intf, width in intfs:
    line += ('|%%%ds' % width) % intf
print(line)

fmt = '%%5s   |%%%ds' % max_name_len
for vid, values in sorted(vids.items()):
    vname, have_intfs = values
    line = fmt % (vid, vname)
    for intf, width in intfs:
        line += ('| %%-%ds' % (width-1)) % (
            '*' if intf in have_intfs else '')
    print(line)

结果:

VLAN-ID | VLAN-NAME |1/1|1/3|1/5|1/6|1/7|1/8|1/10|3/3
    1   |  vlan-wifi| * |   |   |   | * | * |    |   
    2   | vlan-admin|   | * | * | * |   |   |    |   
    3   |           |   | * |   |   |   |   | *  | * 

答案4

您可以使用bash和 数组来执行此操作,如下所示:

#!/bin/bash

# store the numerically sorted file1 into array A
A=( $(sort -t/ -k1,1n -k2,2n < file-1) )

# determine the maximum field width by examining the lengths of the 2nd field
# and the string "VLAN-NAME" coming for the header.
maxW=$(
         { echo ',"VLAN-NAME"'; cat < file-2; } |
         cut -d, -f2 | awk '{print length-2}' |
         sort -nr | sed q
      )

# first two fields of the header
B=( "VLAN-ID " "$(printf " %-${maxW}s\n" "VLAN-NAME")" )

# complete header: from array B and the numerically sorted file1 contents
C=( "${B[@]}" "$(IFS="|"; echo "${A[*]}")" )

# display the header
echo "$(IFS="|"; echo "${B[*]}")" |\
sed -e 's/[^[:blank:]]/ /g;s/$/|   interface switch/'
echo "$(IFS="|"; echo "${C[*]}")"

# remaining lines printed
while IFS=, read -ra B; do
   D=(x)
   for arg in "${A[@]}"; do
      case " ${B[*]:2} " in *" $arg "* ) res=* ;; * ) res=\ ;; esac
      var1=${arg//[!\/]/ } D=( "${D[@]}" "${var1/\//$res}" )
   done
   printf "%8s| %${maxW}s|%s\n" "${B[0]}" "${B[1]//\"/}" "$(IFS="|";echo "${D[*]:1}")"
done < file-2

结果

                    |   interface switch
VLAN-ID | VLAN-NAME |1/1|1/2|1/3|1/4|1/5|1/6|1/7|1/8|1/9|1/10|3/3
       1|  vlan-wifi| * |   |   |   |   |   | * | * |   |    |
       2| vlan-admin|   |   | * |   | * | * |   |   |   |    |
       3|           |   |   | * |   |   |   |   |   |   |    | *

相关内容