#!/usr/bin/perl use warnings; use strict; use Fcntl qw/:DEFAULT :flock/; my $fileA = '/path/to/file_a.txt'; my $fileB = '/path/to/file_b.txt'; my $fileC = '/path/to/file_a.bak'; my $tagline = qr/\QFile A: *** Initial Temperature/; sysopen my $fc, $fileC, O_WRONLY | O_EXCL or die 'Competing process: ', $!; flock $fc, LOCK_EX | LOCK_NB or die 'Competing process: ', $!; open my $fa, '+<', $fileA or die $!; flock $fa, LOCK_EX; while (<$fa>) { print $fc $_; last if /^$tagline/; } open my $fb, '<', $fileB or unlink $fileC and die $!; print $fc $_ while <$fb>; close $fb or unlink $fileC and die $!; print $fc $_ while (<$fa>); close $fc or unlink $fileC and die $!; # reverse the order of the next two statements if # your system won't clobber the open file rename $fileC, $fileA; close $fa;