Perl (Scripting) - Do something every nth line in a file

by
Jeremy Canfield |
Updated: March 09 2020
| Perl (Scripting) articles
Let's say file.txt contains the following text.
removeMe
Hello
World
removeMe
Hello
World
removeMe
Hello
World
removeMe
Hello
World
Remove line 1
In this example, the entire file will be print, except for the very first line. next if 1 == $. means to that line 1 is the current line, and to then go onto the next line.
$file = "/path/to/file.txt";
open(FH, '<', $file) or die "cannot open $file";
while (<FH>) {
if (1 == $.){
next
};
print $_;
}
close(FH);
Running this script will produce the following output.
Hello
World
removeMe
Hello
World
removeMe
Hello
World
removeMe
Hello
World
Remove every third line
With the following Perl script removes line 1 in the file, and then removes every third line thereafter.
$file = "/path/to/file.txt";
open(FH, '<', $file) or die "cannot open $file";
while (<FH>) {
if (1 == $. % 3){
next
};
print $_;
}
close(FH);
Running this script will produce the following output.
Hello
World
Hello
World
Hello
World
Hello
World
Add a new line every fourth line
$file = "/path/to/file.txt";
open(FH, '<', $file) or die "cannot open $file";
while (<FH>) {
if (1 == $. % 4){
print "\n"
};
print $_;
}
close(FH);
The result.
removeMe
Hello
World
removeMe
Hello
World
removeMe
Hello
World
removeMe
Hello
World
Did you find this article helpful?
If so, consider buying me a coffee over at