将值从两行附加到密钥对中

时间:2013-11-11 16:34:21

标签: python perl bash

我的文本文件输出看起来像这两行:

DelayTimeThreshold|MaxDelayPerMinute|Name
10000|5|rca

我想要的输出看起来像这样:

DelayTimeThreshold 10000
MaxDelayPerMinute 5
Name rca

我没有运气试试这个:

sed '$!N;s/|/\n/' foo

欢迎任何建议,谢谢。

5 个答案:

答案 0 :(得分:1)

由于你只有两行,这可能是一种方式:

$ paste -d' ' <(head -1 file | sed 's/|/\n/g') <(tail -1 file | sed 's/|/\n/g')
DelayTimeThreshold 10000
MaxDelayPerMinute 5
Name rca

分段。让我们得到第一行并用新行替换每个管道|

$ head -1 file | sed 's/|/\n/g'
DelayTimeThreshold
MaxDelayPerMinute
Name

对最后一行做同样的事情:

$ tail -1 file | sed 's/|/\n/g'
10000
5
rca

然后,只需用空格作为分隔符粘贴两个结果:

paste -d' ' output1 output2

答案 1 :(得分:1)

这个awk单行程可以满足您的要求:

awk -F'|' '!f{gsub(/\||$/," %s\n");f=$0;next}{printf f,$1,$2,$3}' file

输出:

kent$ echo "DelayTimeThreshold|MaxDelayPerMinute|Name
10000|5|rca"|awk -F'|' '!f{gsub(/\||$/," %s\n");f=$0;next}{printf f,$1,$2,$3}'  
DelayTimeThreshold 10000
MaxDelayPerMinute 5
Name rca

答案 2 :(得分:1)

使用Array::Transpose模块:

perl -MArray::Transpose -F'\|' -lane '
    push @a, [@F]
    } END {print for map {join " ", @$_} transpose(\@a)
' <<END
DelayTimeThreshold|MaxDelayPerMinute|Name
10000|5|rca
END
DelayTimeThreshold 10000
MaxDelayPerMinute 5
Name rca

答案 3 :(得分:0)

作为perl脚本:

#!/usr/bin/perl -w
use strict; 
use Data::Dumper;

my $file1 = ('DelayTimeThreshold|MaxDelayPerMinute|Name');
my $file2 = ('10000|5|rca');

my @file1 = split('\|', $file1);
my @file2 = split('\|', $file2);

my %hash;

@hash{@file1} = @file2;

print Dumper \%hash;

输出:

$VAR1 = {
          'Name' => 'rca',
          'DelayTimeThreshold' => '10000',
          'MaxDelayPerMinute' => '5'
        };

OR:

for (my $i = 0; $i < $#file1; $i++) {
    print "$file1[$i] $file2[$i]\n";
}

输出:

DelayTimeThreshold 10000
MaxDelayPerMinute 5
Name rca

答案 4 :(得分:0)

假设您的文件包含带有列名的单个标题行,后跟带有列值的多个详细信息行,例如

DelayTimeThreshold|MaxDelayPerMinute|Name
10000|5|abc
20001|6|def
30002|7|ghk
40003|8|jkl
50004|9|mnp

以下代码将使用第一行中的名称打印该文件,并与每个后续(明细)行的值配对,

#!/bin/perl -w
use strict;
my ($fn,$fh)=("header.csv"); #whatever the file is named...
open($fh,"< $fn") || error "cannot open $fn";
my ($count,$line,@names,@vals)=(0);
while(<$fh>)
{
    chomp $_;
    @vals=split(/\|/,$_);
    if($count++<1) { @names=@vals; next; } #first line is names
    for (my $ndx=0; $ndx<=$#names; $ndx++) { #print each
        print "$names[$ndx] $vals[$ndx]\n";
    }
}

假设您想要在数组中使用名称注释每行(

my %row;
my @records;
while(<$fh>)
{
    chomp $_;
    @vals=split(/\|/,$_);
    if($count++<1) { @names=@vals; next; }
    @row{@names} = @vals;
    push(@records,\%row);
}

也许您想通过某个键列引用行

my %row;
my %records;
while(<$fh>)
{
    chomp $_;
    @vals=split(/\|/,$_);
    if($count++<1) { @names=@vals; next; }
    @row{@names} = @vals;
    $records{$vals[0]}=\%row;
}