The Following is found on the internet and it seems to be useful. Just put here to be used next time. The source is from the link: http://stackoverflow.com/questions/4388304/in-perl-how-do-i-change-delete-or-insert-a-line-in-a-file-or-append-to-the-b
perl -pi -e 's/Fred/Barney/' inFile.txt
To make a backup of inFile.txt, give -i a file extension to add:
perl -pi.bak -e 's/Fred/Barney/' inFile.txt
To change only the fifth line, you can add a test checking
$.
, the input line number, then only perform the operation when the test passes:perl -pi -e 's/Fred/Barney/ if $. == 5' inFile.txt
To add lines before a certain line, you can add a line (or lines!) before Perl prints
$_
:perl -pi -e 'print "Put before third line\n" if $. == 3' inFile.txt
You can even add a line to the beginning of a file, since the current line prints at the end of the loop:
perl -pi -e 'print "Put before first line\n" if $. == 1' inFile.txt
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.perl -ni -e 'print; print "Put after fifth line\n" if $. == 5' inFile.txt
To delete lines, only print the ones that you want.
perl -ni -e 'print unless /d/' inFile.txt
… or …
perl -pi -e 'next unless /d/' inFile.txt
No comments:
Post a Comment