Answer the question
In order to leave comments, you need to log in
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
#!/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);
Answer the question
In order to leave comments, you need to log in
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.
#!/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 <>;
$ 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 questionAsk a Question
731 491 924 answers to any question