Contents
How do I delete a line in a file in Perl?
To delete lines, only print the ones that you want. The perl -ni -e ‘print unless /d/’ inFile.txt did indeed work for deleting matching lines, but the perl -pi -e ‘next unless /d/’ inFile.txt did not. Nor did changing next unless to next if.
How to insert a line after one already in a file in Perl?
To insert a line after one already in the file, use the -n switch. It’s just like -p except that it doesn’t print $_ at the end of the loop, so you have to do that yourself. In this case, print $_ first, then print the line that you want to add.
How is a Perl program used to print lines?
A Perl program to do these tasks takes the basic form of opening a file, printing its lines, then closing the file: Within that basic form, add the parts that you need to insert, change, or delete lines. To prepend lines to the beginning, print those lines before you enter the loop that prints the existing lines.
How to change the current line in Perl?
With the -p switch, Perl wraps a while loop around the code you specify with -e, and -i turns on in-place editing. The current line is in $_. With -p, Perl automatically prints the value of $_ at the end of the loop.
Can you add a line before a line in Perl?
To add lines before a certain line, you can add a line (or lines!) before Perl prints $_: You can even add a line to the beginning of a file, since the current line prints at the end of the loop: To insert a line after one already in the file, use the -n switch.
How can I modify a file in Perl?
Modules such as File::Slurp and Tie::File can help with that too. If you can, however, avoid reading the entire file at once. Perl won’t give that memory back to the operating system until the process finishes. You can also use Perl one-liners to modify a file in-place.