#!/usr/bin/perl # The Missing Textutils, Ondrej Bojar, obo@cuni.cz # http://www.cuni.cz/~obo/textutils # # 'insert_lines' is a complement to 'grep -n'. Given a file of lines extracted # using 'grep -n', it places the lines back to the rest at appropriate places. # # If you are curious why this is useful, consider editing or processing the # grepped lines separately. # # $Id: insert_lines,v 1.4 2010-11-02 17:04:03 bojar Exp $ # use strict; use Getopt::Long; my $replace = 1; # the default is to replace the input lines # if !replace, the lines are inserted before the corresponding line in stdin my $usage = 0; GetOptions( "help" => \$usage, "replace!" => \$replace, ) or exit 1; my $fn = shift; if (!defined $fn || $usage) { print STDERR "Usage: insert_lines lines_to_implant < input > output\n"; exit 1; } my %insert; open FN, $fn or die "Can't read '$fn'"; while () { chomp; my ($lineno, $string) = split /:/, $_, 2; if (defined $insert{$lineno}) { print STDERR "$fn: Conflicting data for line $lineno.\n"; print STDERR " Seen before: $insert{$lineno}\n Seen now: $string\n"; } $insert{$lineno} = $string; } close FN; my $nr = 0; while (<>) { $nr++; if (defined $insert{$nr}) { print $insert{$nr}."\n"; print if !$replace; next; } print; }