簡體   English   中英

在Linux中解析

[英]Parsing in Linux

我想解析開放堆棧命令輸出中的計算區域,如下所示

+-----------------------+----------------------------------------+
| Name                  | Status                                 |
+-----------------------+----------------------------------------+
| internal              | available                              |
| |- controller         |                                        |
| | |- nova-conductor   | enabled :-) 2016-07-07T08:09:57.000000 |
| | |- nova-consoleauth | enabled :-) 2016-07-07T08:10:01.000000 |
| | |- nova-scheduler   | enabled :-) 2016-07-07T08:10:00.000000 |
| | |- nova-cert        | enabled :-) 2016-07-07T08:10:00.000000 |
| Compute01             | available                              |
| |- compute01          |                                        |
| | |- nova-compute     | enabled :-) 2016-07-07T08:09:53.000000 |
| Compute02             | available                              |
| |- compute02          |                                        |
| | |- nova-compute     | enabled :-) 2016-07-07T08:10:00.000000 |
| nova                  | not available                          |
+-----------------------+----------------------------------------+

我想解析結果如下,僅采用具有nova-compute的節點

Compute01;Compute02

我用下面的命令:

nova availability-zone-list | awk 'NR>2 {print $2}' | grep -v '|' | tr '\n' ';'

但它返回這樣的輸出

;internal;Compute01;Compute02;nova;;

在Perl中(並且寫得比實際需要的還要冗長):

#!/usr/bin/perl

use strict;
use warnings;
use 5.010;

my $node; # Store current node name
my @compute_nodes; # Store known nova-compute nodes

while (<>) { # Read from STDIN
  # If we find the start of line, followed by a pipe, a space and
  # a series of word characters...
  if (/^\| (\w+)/) {
    # Store the series of word characters (i.e. the node name) in $node
    $node = $1;
  }

  # If we find a line that contains "nova-compute", add the current
  # node name in @compute_nodes
  push @compute_nodes, $node if /nova-compute/;
}

# Print out all of the values in @compute_nodes    
say join ';', @compute_nodes;

除了最簡單的應用程序之外,我討厭一線程序。 它們不必要地是加密的,沒有通常的編程支持,並且僅存儲在終端緩沖區中。 想明天做同樣的事情嗎? 您必須重新開始編碼

這是一個Perl解決方案。 運行為

$ perl nova-compute.pl command-output.txt
use strict;
use warnings 'all';

my ($node, @nodes);

while ( <> ) {
    $node = $1 if /^ \| \s* (\w+) /x;
    push @nodes, $node if /nova-compute/;
}

print join(';', @nodes), "\n";

輸出

Compute01;Compute02

現在所有這些都保存在磁盤上。 它可能會在任何時間再次運行,為獲得類似結果而進行修改,或者如果發現錯誤可以進行修復。 它也是可讀的。 沒有比賽

$  nova availability-zone-list | awk '/^[|] [^|]/{node=$2} node && /nova-compute/ {s=s ";" node} END{print substr(s,2)}' 
Compute01;Compute02

這個怎么運作:

  • /^[|] [^|]/{node=$2}

    只要一行以|開頭 后跟空格,后跟一個非字符| ,然后將第二個字段另存為節點名稱。

  • node && /nova-compute/ {s=s ";" node}

    如果node為非空並且當前行包含nova-compute ,則將node附加到字符串s

  • END{print substr(s,2)}

    閱讀完所有行后,打印出字符串s減去多余的第一個字符;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM