Search code examples
perlinlineinsertafter

One line script to edit after the Pattern


I got an example here but wouldn't write the output/print to a file

perl -lne 'print $_;print "This is Middle" if(/Beginning/);' file

I tried putting > file but it happens to overwrite it all empty.


Solution

  • You can't read from a file and write to it at the same time. The usual way to handle this kind of thing is write to a temporary file and replace the original with it after the action:

    perl -lne 'print $_;print "This is Middle" if(/Beginning/);' file > file.tmp; \
    mv -f file.tmp file
    

    See also.