Reputation: 3
I have a file that consists of many tables that contain data about certain coordinates. Each table is separated by a line with the word "Coords".
Coords
Table 1
Coords
Table 2
Coords
Table 3
...
In a separate file, I have a list of all of the coordinates that match the tables.
Coordinate 1
Coordinate 2
Coordinate 3
...
What I am trying to do is replace the first instance of "Coords" with the first line of the coordinates file, the second instance with the second line, etc.
Coordinate 1
Table 1
Coordinate 2
Table 2
Coordinate 3
Table 3
...
I've tried this:
while read coord
do
perl -pln -e 's/Coords/$coord/' Tables >> Output
done <Coordinates
But it didn't work. (Because perl cannot use bash variables?) Any help would be greatly appreciated.
Upvotes: 0
Views: 244
Reputation: 58430
This might work for you (GNU sed):
sed -e '/Coords/{Rcoord.txt' -e 'd}' template.txt
Upvotes: 1
Reputation: 56089
This is a trivial one-liner with awk
:
awk '/Coords/{getline<"coords.txt"}1' template.txt
A slightly less fun one that reads the coordinates file into memory:
awk 'NR==FNR{repl[NR]=$0;next}/Coords/{$0=repl[++n]}1' coords.txt template.txt
Upvotes: 1
Reputation: 61512
You can do this pretty easily, you just need to break it down into manageable steps.
What I am trying to do is replace the first instance of "Coords" with the first line of the coordinates file, the second instance with the second line, etc.
Lets see if we can break this up:
Coords
shift
will extract the first value from the coordinates list) Here is what that might look like:
#!/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);
Upvotes: 0