【问题标题】:Adding a new position at the end of the file Shell or Perl在文件 Shell 或 Perl 的末尾添加一个新位置
【发布时间】:2018-02-11 17:45:38
【问题描述】:

我的问题是如何在 Shell 或 Perl 的文件末尾添加一个新位置?

我有两个文件: 文件 A 有 536382 行,关键是第三列:

abc1111,1070X00Y0,**9999**,B
abc2222,1070X00Y0,**9999**,B
abc3333,1070x00Y0,**9999**,B

文件B有946行,关键是第一列:

**9999**,Position,West
**9998**,Position,West
**9997**,Position,South
**1111**,Position,South
**9999**,Time,Morning
**9997**,Time,Afternoon

我想要这两个文件的组合:

abc1111,1070X00Y0,9999,B,West,Morning
abc2222,1070X00Y0,9999,B,West,Morning
abc3333,1070x00Y0,9999,B,West,Morning

我正在尝试使用 shell 脚本,但收到一条内存不足的消息。 所以我打开了建议。

谢谢,到目前为止。

【问题讨论】:

  • 文件 B 有多大?
  • 大约 1000 行

标签: shell perl


【解决方案1】:

通过对您的代码进行一些更改,我能够得到您想要的结果。

#!/usr/bin/perl
use strict;
use warnings;

open IN2, '<', \<<EOF;
**9999**,Position,West
**9998**,Position,West
**9997**,Position,South
**1111**,Position,South
**9999**,Time,Morning
**9997**,Time,Afternoon
EOF

my %hash;

while ( <IN2> ) {
     chomp;
     my @col2 = split ","; 
     $hash{$col2[0]}{$col2[1]} = $col2[2]; 
} 

open IN1, '<', \<<EOF;
abc1111,1070X00Y0,**9999**,B
abc2222,1070X00Y0,**9999**,B
abc3333,1070x00Y0,**9999**,B
EOF

while ( <IN1> ) { 
    chomp;
    my $key = (split /,/)[2];
    if ( exists( $hash{$key} ) ) { 
        print join(",", $_, @{ $hash{$key} }{ qw/Position Time/ }), "\n";
    }
} 

这产生了以下输出:

abc1111,1070X00Y0,**9999**,B,West,Morning
abc2222,1070X00Y0,**9999**,B,West,Morning
abc3333,1070x00Y0,**9999**,B,West,Morning

对代码的更改是

  1. $hash{$col2[0]}{$col2[1]} = $col2[2]; 创建一个 Hash of Hash 来保存 PositionTime 键。它们在这里用于哈希切片

  2. @{ $hash{$key} }{ qw/Position Time/ })

【讨论】:

  • 成功了。太感谢了。我有很多要学习的。你有什么网站推荐吗?
【解决方案2】:
  1. 将小文件转换为 perl 的哈希
  2. 逐行处理大文件

【讨论】:

  • 我已经这样做了,但它停在这个值 West 并且不处理第二个循环 Morning。 while ( ) { chomp;我的@ col2 =拆分“,”; $hash{$col2[0]} = $col2[2]; } while ( ) { chomp;我的@ col1 =拆分“,”; if ( 存在( $hash{$col1[2]} ) ) { 打印出 $col1[2] 。 “,”。 $col1[1] 。 “,”。 $col1[0] 。 “,”。 $col1[3] 。 “,”。 $hash{$col1[2]} 。 "\n"; } }
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-01-06
  • 2017-10-14
  • 1970-01-01
相关资源
最近更新 更多