1

In a bash script, I try to call the following Perl command on each file, and then I want to redirect the Perl command's output to that file.

The Perl command simply removes the comments from the file. When it prints to the console it seems to work. But when I try to redirect the output to each individual file, the file becomes empty. What am I doing wrong here?

#!/usr/bin/env bash

shopt -s globstar
for file in ./**/*.java; do
    perl -0pe 's|//.*?\n|\n|g; s#/\*(.|\n)*?\*/##g; s/\n\n+/\n\n/g' "$file" > "$file";
done
rapt
  • 11,810
  • 35
  • 103
  • 145
  • 1
    Tip: `-0` doesn't actually slurp the file. You should use `-0777` instead. – ikegami Dec 27 '17 at 07:58
  • @ikegami How was it able then to process the file not line by line? – rapt Dec 27 '17 at 08:21
  • 1
    Read up on the difference between `$/ = "\0";` (`-0`) and `$/ = undef;` (`-0777`). It's not the intent of the first to slurp (and won't always). – ikegami Dec 29 '17 at 10:41

1 Answers1

2

You are trying to read from a file and trying to re-direct the output to the same file. This does not work. Shell first opens the file for writing, now when Perl tries to read from the file, there is nothing present, and hence no output.

You can use the -i option of Perl to do in-place edit.

perl -i.bak -0pe 's|//.*?\n|\n|g; s#/\*(.|\n)*?\*/##g; s/\n\n+/\n\n/g' "$file"

This will edit the file directly and also have the original copy of the file with a .bak extension. If you do not need any backup, simply use -i in place of -i.bak

Guru
  • 16,456
  • 2
  • 33
  • 46