B
B
BusterX2016-05-24 13:56:41
Perl
BusterX, 2016-05-24 13:56:41

How to add a line to a file using Perl?

Hello.
The question seems to be simple, but I can not win in any way.
There is a text file users.list containing sections with a list of users:

<Title1>
username1
username2
<Title2>
username2
username3

Using a perl script, you need to add username4 to the Title1 section , without overwriting existing users.
My script:
#!/usr/bin/perl -w
use strict;
use warnings;
if(open(FILE, "+< users.list") or die "Error: $!"){
    flock(FILE, 2);
}
while(<FILE>){
    if(~/Title1/){
        print FILE "username4";
        last;
    }
}
close(FILE);

This option will overwrite username1 with username4 . I tried to add line breaks and carriage returns, but the result is not what you need.
P.S. I thought about the option "overtake to an array and back", but I want to know if it can be implemented without an array.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Alexey, 2016-05-24
@alsopub

Without an array.
Read one line at a time from a file, write one line at a time to a temporary file.
When the required section is found, write an additional line to the temporary file.
Rename temporary file to original.
It is better to place a temporary file nearby (in the same directory) for rename to work.
It seems to me that if in your example you replace "username4" with "u4", then you get porridge.
Files cannot just be taken and "stretched" or "compressed" in the middle.
The maximum that can be done is to cut off from the end or add to the end.

O
Oleg, 2016-05-24
@hobo-mts

#!/usr/bin/perl

use strict;
use warnings;

while (<>) {
    print;
    last if /<Title1>/i;
}
while (<>) {
    if (/<Title/i) {
        print "username4\n";
        print;
        last;
    }
    else {
        print;
    }
}
print while <>;

Usage:
If the file is small, then it can be simpler:
Or:
$ perl -e '$/ = ""; <> =~ /(<Title1>[^<]+)(.+)/is && print $1, "user4\n", $2;' <users.list
<Title1>
username1
username2
username4
user4
<Title2>
username2
username3

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question