1

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

DelayTimeThreshold|MaxDelayPerMinute|Name
10000|5|rca

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

DelayTimeThreshold 10000
MaxDelayPerMinute 5
Name rca

我没有运气尝试这个:

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

欢迎任何建议,谢谢。

4

5 回答 5

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
于 2013-11-11T16:37:23.080 回答
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
于 2013-11-11T16:58:44.807 回答
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
于 2013-11-11T17:17:18.620 回答
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;
}
于 2013-11-11T17:27:30.257 回答
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'
        };

或者:

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

输出:

DelayTimeThreshold 10000
MaxDelayPerMinute 5
Name rca
于 2013-11-11T16:46:37.940 回答