2013-04-03 117 views
3

我有以下列格式的管道分隔日誌文件:Perl腳本配置grep的輸出

<date> <time> | <fruit> | <color> | <num_1> | <num_2> | <num_3> 

因此,例如:

2013-03-27 23:01:52 | apple | green | 55 | 120 | 29 
2013-03-27 23:01:56 | plumb | purple | 28 | 1 | 394 
2013-03-27 23:01:59 | apple | red | 553 | 21 | 7822 

我想編寫一個Perl腳本(儘管python或bash也是可以接受的),根據您給腳本的輸入,greps列出<date><time>字段(列1)和<num_1>,<num_2><num_3>。因此,上述信息運行perl extract.pl 2會給你<date><time><num_2>

2013-03-27 23:01:52 | 120 
2013-03-27 23:01:56 | 1 
2013-03-27 23:01:59 | 21 

我嘗試以下,但它似乎並沒有工作:

#!/usr/bin/perl 

use warnings; 
use strict; 

my $col = $1; 

print `grep "myapplog.txt" "m/_(\d{4})(\d\d)(\d\d)/ | $col"` 

在這裏,我設置col var到腳本的第一個參數,然後嘗試打印匹配第一列的日期時間和期望<num_X>列的grep。有任何想法嗎?提前致謝。

+1

'$ 1'不是腳本的第一個參數。那將是'$ ARGV [0]'。 「$ 1」是第一個正則表達式捕獲緩衝區的內容。 – 2013-04-03 20:05:44

回答

4

嘗試在AWK-模式用perl

$ perl -F'\|' -lane 'print $F[0]," | ", $F[4]' input 
2013-03-27 23:01:52 | 120 
2013-03-27 23:01:56 | 1 
2013-03-27 23:01:59 | 21 

純AWK:

awk -F"|" '{print $1, "|", $5}' input 

純慶典:

#!/bin/bash 

IFS="|" 

while read -a ARRAY; 
do 
    echo ${ARRAY[0]} "|" ${ARRAY[4]} 
done < input 

更新

的通過例如到AWK-溶液的參數,以確定巫柱進行打印,使用:

$ awk -vcol="5" -F"|" '{print $1, "|", $col}' input 

在bash,所述第一參數的功能/腳本駐留在$1這樣使用,作爲一個索引數組。不是一個班輪

東西更正式,使用python:

#!/usr/bin/env python 

import sys 

col = raw_input('which column to print? -> ') 
try: 
    col = int(col) 
except ValueError: 
    print >> sys.stderr, "That was no integer" 

with open("input") as fd: 
    for line in fd: 
     tmp = line.strip().split('|') 
     print tmp[0], "|", tmp[col] 
+0

謝謝@Fredrik Pihl(+1) - 我會對perl-awk組合感興趣,但應該提到我的日誌文件很大,並且不包含那3行日誌條目。所以它看起來像你的第一個建議(perl-awk)的規則。對於其他2,我沒有任何偏好,但不知道如何從命令行調用它們以及如何將它們作爲輸入。再次感謝! – IAmYourFaja 2013-04-03 20:09:27

+0

看到更新,也許這就解決了這個問題... – 2013-04-03 20:17:27

1

嘗試使用類似的第一個參數在你的願望做這

(使用@ARGV陣列,在perl$1):

#!/usr/bin/perl 

use warnings; use strict; 
use autodie; # No need to check open() errors 

$\ = "\n"; # output record separator (no need \n) 

# file-handle 
open my $fh, "<", "myapplog.txt"; 

chomp(my $col = $ARGV[0]); 

die("Not an integer !\n") unless $col =~ /^\d+$/; 

# using the famous and magical <diamond> operator: 
while (<$fh>) { 
    chomp; 
    my @F = split /\|/; # splitting current line in @F array 
    print join("|", @F[0,$col+2]); # join on a array slice 
} 

close $fh; 
+0

也增加了腳本參數版本... – 2013-04-03 20:22:16

+1

+1對於很好的perl編碼 – 2013-04-03 20:30:36

+0

已編輯:使用數組切片並立即加入。 – 2013-04-03 20:35:29