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
3
  • 1
    Tip: -0 doesn't actually slurp the file. You should use -0777 instead. Commented Dec 27, 2017 at 7:58
  • @ikegami How was it able then to process the file not line by line? Commented Dec 27, 2017 at 8: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). Commented Dec 29, 2017 at 10:41

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you! Now it makes sense!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.