Reputation: 12230
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
Upvotes: 1
Views: 547
Reputation: 17044
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
Upvotes: 2