Do something every nth line in a file using Perl

Home > Search
  by

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

 



Add a Comment




We will never share your name or email with anyone. Enter your email if you would like to be notified when we respond to your comment.




Please enter in the box below so that we can be sure you are a human.




Comments