Monday, January 3, 2011

perl: Inserting a Line at a Specific Line Number



1. Insert into a Single File

To add the line "New line added!!" right before or at line 100 of example.txt:

Bash
perl -pi -le 'print "New line added!!" if $. == 100' example.txt


2. Insert into Multiple Files

If you need to apply this change across multiple files (e.g., all .txt files), include the close ARGV if eof command:

Bash
perl -pi -le 'print "New line added!!" if $. == 100; close ARGV if eof' *.txt

 

Why is close ARGV if eof needed?
By default, Perl's line counter variable ($.) accumulates across all files when processing multiple inputs. Closing ARGV at the end of each file resets $. back to 1 for the next file.

💡 Quick Flag Breakdown

  • -p: Loops through the file line-by-line and automatically prints each line ($_).

  • -i: Enables in-place editing (modifies the file directly instead of printing to standard output).

  • -l: Automatically handles line endings (appends newlines on output and chomp inputs).

  • -e: Executes the Perl expression provided in quotes.

  • $.: The current line number of the file being read.

No comments: