【问题标题】:replace matches with values from other file用其他文件中的值替换匹配项
【发布时间】:2013-06-25 17:25:09
【问题描述】:

我有一个文件,其中包含许多表,其中包含有关某些坐标的数据。每个表都由一行用“Coords”隔开。

Coords
Table 1
Coords 
Table 2
Coords
Table 3
...

在一个单独的文件中,我列出了与表格匹配的所有坐标。

Coordinate 1
Coordinate 2
Coordinate 3
...

我想要做的是用坐标文件的第一行替换“Coords”的第一个实例,用第二行替换第二个实例,等等。

Coordinate 1
Table 1
Coordinate 2
Table 2
Coordinate 3
Table 3
...

我试过了:

while read coord
do
    perl -pln -e 's/Coords/$coord/' Tables >> Output
done <Coordinates

但它没有用。 (因为 perl 不能使用 bash 变量?)任何帮助将不胜感激。

【问题讨论】:

  • 你试过用双引号代替吗?此外,-p-n 是互斥的(因为它们做同样的事情,除了打印)。
  • 是的,但还是没有运气

标签: perl bash sed awk


【解决方案1】:

这是awk 的简单单行代码:

awk '/Coords/{getline<"coords.txt"}1' template.txt

将坐标文件读入内存的乐趣稍逊:

awk 'NR==FNR{repl[NR]=$0;next}/Coords/{$0=repl[++n]}1' coords.txt template.txt

【讨论】:

    【解决方案2】:

    这可能对你有用(GNU sed):

    sed -e '/Coords/{Rcoord.txt' -e 'd}' template.txt
    

    【讨论】:

      【解决方案3】:

      您可以很容易地做到这一点,您只需将其分解为可管理的步骤。

      我想要做的是将“坐标”的第一个实例替换为 坐标文件的第一行,第二个实例 第二行等。

      让我们看看我们是否可以打破这个:

      1. 从坐标文件中读取数据(可能到列表中)
      2. 逐行遍历占位符文件,搜索Coords
      3. 如果找到匹配项,请用坐标文件中的下一行覆盖该行(使用shift 将从坐标列表中提取第一个值)

      这是可能的样子:

      #!/usr/bin/perl
      use strict;
      use warnings FATAL => 'all';
      
      # open the coordinates file for reading
      open(my $coord_fh, '<', 'coordinates.txt');
      
      # read the file (line by line) into a List
      my @coordinates = <$coord_fh>;
      
      # close coordinate filehandle
      close($coord_fh);
      
      # open the other file for reading
      open(my $other_fh, '<', 'otherfile.txt');
      
      # save the lines you process
      my @lines;
      
      # first coordinate
      my $coord = shift @coordinates;
      
      # read line by line seraching for Coord
      # replace with shift @coordinates if found
      while ( my $line = <$other_fh> ) {
          if( $line =~ s/Coords/$coord/ ) {
              # get next coordinate
              $coord = shift @coordinates;
          }
      
          # save line
          push @lines, $line;
      }
      
      # close file for reading
      close($other_fh);
      
      
      # write all of the lines back to your file
      open(my $out_fh, '>', 'otherfile.txt');
      
      print {$out_fh} "$_" foreach(@lines);
      

      【讨论】:

      • 我收到以下错误“在 PerlCoorder 第 26 行, 第 364525 行使用未初始化的值 $coord 替换 (s///)。”但是我注释掉了 use strict 和 use warnings ,它似乎工作得很好。非常感谢!
      • 去除严格和警告以摆脱警告就像在汽车的机油警告灯上贴一张贴纸。换句话说,这不是一个好主意。
      • @JT 它在我的机器上执行,没有错误或警告。你做了什么改变吗?
      • @JT,您在坐标.txt 中的行数可能少于在 otherfile.txt 中出现的“坐标”。当@coordinates 为空时,您开始尝试替换undef,这会生成该警告。
      • @cjm 其实就是这样。感谢您的帮助
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-05-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-01-09
      • 2016-09-20
      • 2017-07-11
      相关资源
      最近更新 更多