使用Perl批量替换1-19号i_f.xyz文件内容失败,求助
Hey there! Let's break down why your command isn't working and get those files updated properly.
The core problem here is that when you run perl -pi -e 's/6/C/g' ${i}_f.xyz directly, your shell doesn't know what ${i} is unless you've defined it in a loop. Without a loop, ${i} is either empty or treated as an undefined variable, so Perl ends up trying to modify a file named _f.xyz (which probably doesn't exist) instead of your 1-19 numbered files.
Here are two straightforward solutions to fix this:
1. Use a Shell Loop (Most Reliable for Beginners)
Wrap your Perl command in a bash/zsh loop that iterates from 1 to 19. This will set ${i} to each number in sequence and run the replacement on the correct file:
for i in {1..19}; do perl -pi -e 's/6/C/g' "${i}_f.xyz" done
- The
{1..19}syntax tells the shell to generate numbers from 1 through 19. - Wrapping
"${i}_f.xyz"in quotes is a good habit (even if your filenames don't have spaces now, it prevents unexpected behavior later).
2. Target All Files Directly with Perl
If you prefer to avoid a loop, you can use shell globbing to pass all 19 files to Perl in one command:
perl -pi -e 's/6/C/g' [1-9]_f.xyz 1[0-9]_f.xyz
[1-9]_f.xyzmatches files 1-9, and1[0-9]_f.xyzmatches files 10-19.
Extra Tips to Avoid Headaches
- Preview Changes First: If you want to check what would be replaced without modifying files, remove the
-iflag:perl -pe 's/6/C/g' 1_f.xyz - Keep Backups: Use
-i.bakinstead of-ito create a backup of each original file (e.g.,1_f.xyz.bak) before modifying:perl -pi.bak -e 's/6/C/g' "${i}_f.xyz" - Verify File Existence: Double-check all your files exist by running:
If any are missing, you'll see an error, which might explain why some replacements didn't happen.ls {1..19}_f.xyz
内容的提问来源于stack exchange,提问作者Pierre-Louis LEFEBVRE

