lovingboth: (Default)
[personal profile] lovingboth
A bash script I use ends by displaying a line it wants you to add to another file. It would obviously be easier if the script did this itself. As the line will be somewhere in the middle of the file, just using '>>' to append it is no good.

Somewhere :) I have (or had) The AWK Programming Language and my Google skills are enough to be reminded that:

awk '/NEW STUFF HERE/ {print;print "my new line";next}1' test-file


will add 'my new line' after 'NEW STUFF HERE'.

Now, 'my new line' needs to have a number in it that is different to all the other such lines (it's an array index).

Can someone remind me of a good way to do that? The line count of the entire file prior to adding the line would be fine, for example.

(no subject)

Date: 2009-05-15 09:39 pm (UTC)
From: [identity profile] mattp.livejournal.com
This solution has the new line and your insertion point in the other way round compared to the original post. If that's what you need then just switch the first print and the if block in my program.
From: [identity profile] mattp.livejournal.com
#!/usr/bin/perl 
use strict;
use warnings;

my @text            = ;
my $multipleinserts = 0;
my $alreadyseen     = 0;

for (my $i = 0 ; $i < $. ; $i++) {
        print $text[$i];
        if ($text[$i] =~ /pattern to insert after/ && $multipleinserts || !$alreadyseen) {
                print 1+$. .": new line here\n";
                $alreadyseen = 1;
        }
}



If the search patter appears twice then the text gets inserted after the first, or you can edit the obviously named variable to have it inserted after every occurrence. You didn't state what format the numbers take so I guessed. It shouldn't be too hard to change to suit your requirements. One caveat - it doesn't check for duplicate index values.

Profile

lovingboth: (Default)
Ian

June 2025

S M T W T F S
1234567
891011121314
15161718192021
22232425262728
2930     

Most Popular Tags

Style Credit

Expand Cut Tags

No cut tags