in reply to put a newline character after every four lines in a file

With a oneliner:

$ perl -i -ple '$_.="\n" if $. % 4 == 0; close ARGV if eof' -- FILES

Documentation: Command-line switches in perlrun, $. for the current line number, eof in regards to resetting $., and Multiplicative Operators for the modulo operator.

Replies are listed 'Best First'.
Re^2: put a newline character after every four lines in a file
by Anonymous Monk on Feb 24, 2017 at 06:40 UTC
    Thanks...it works but when running in script with system command, it is giving errors....please suggest
      when running in script with system command

      What do you mean by this - are you running system("perl ... from inside a Perl script? That's not necessary, and a bit wasteful. How to best integrate the two depends on how you are further processing the files, so if you could explain and show an SSCCE, we could help you better.

      One way to do the same thing as the oneliner I posted above without calling another Perl process would be:

      { # new scope for local local *ARGV; @ARGV = @files; local $^I = ""; # -i command line switch while (<>) { print $_; print "\n" if $. % 4 == 0; close ARGV if eof; } }

      However, if you plan on further processing the files in the same script, this will be inefficient!

      Update: Fixed typo

      Update 2: Fixed this potential issue in the above example code.

      thanks alot...resolved the errors