0

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

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

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

Coordinate 1
Coordinate 2
Coordinate 3
...

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

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 变量?)任何帮助将不胜感激。

4

3 回答 3

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
于 2013-06-25T18:02:58.340 回答
1

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

sed -e '/Coords/{Rcoord.txt' -e 'd}' template.txt
于 2013-06-25T20:42:31.313 回答
0

你可以很容易地做到这一点,你只需要把它分解成可管理的步骤。

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

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

  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);
于 2013-06-25T17:42:31.677 回答