3

I was given a Perl one-liner. It has the following form:

perl -pe'...'

How do I specify the file to process to the program?

ikegami
  • 367,544
  • 15
  • 269
  • 518
  • 2
    I got tired of pasting the answer into every question answered with a Perl one-liner solution. – ikegami Jan 19 '17 at 13:26

1 Answers1

7

Documentation on how to launch perl is found in the perlrun man page.

perl -pe'...' -i~ file [file [...]]   # Modifies named file(s) in place with backup.
perl -pe'...' -i file [file [...]]    # Modifies named file(s) in place without backup.
perl -pe'...' file.in >file.out       # Reads from named file(s), outputs to STDOUT.
perl -pe'...' <file.in >file.out      # Reads from STDIN, outputs to STDOUT.

If the file's name could start with a -, you can use --.

perl -pe'...' [-i[~]] -- "$file" [...]

If you wanted to modify multiple files, you could use any of the following:

find ... -exec               perl -pe'...' -i~ {} +   # GNU find required
find ...         | xargs -r  perl -pe'...' -i~        # Doesn't support newlines in names
find ... -print0 | xargs -r0 perl -pe'...' -i~

In all of the above, square brackets ([]) denote something optional. They should not appear in the actual command. On the other hand, the {} in the -exec clause should appear as-is.


Note: Some one-liners use -n and explicit prints instead of -p. All of the above applies to these as well.

ikegami
  • 367,544
  • 15
  • 269
  • 518
  • This is very useful. Can you also add how to use perl in -exec option of find command. – stack0114106 Oct 29 '20 at 03:10
  • @stack0114106, It's already there. It's the first one. – ikegami Oct 29 '20 at 03:58
  • Thank you.. I thought that requires a for loop. – stack0114106 Oct 29 '20 at 05:58
  • @stack0114106, Perl's `-n`/`-p` will happily read from each file provided on the command line in turn. All three version can pass multiple files to a single invocation of `perl`. Use `-exec perl ... \;` (GNU `find` or otherwise) to get only one file per invocation of `perl` (e.g. if you want to do something on a per-file basis in `END{}`.) – ikegami Nov 09 '20 at 15:56