You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Perl批量替换1-19号i_f.xyz文件内容失败,求助

Fixing Your Perl Batch File Replacement Issue

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.xyz matches files 1-9, and 1[0-9]_f.xyz matches 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 -i flag:
    perl -pe 's/6/C/g' 1_f.xyz
    
  • Keep Backups: Use -i.bak instead of -i to 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:
    ls {1..19}_f.xyz
    
    If any are missing, you'll see an error, which might explain why some replacements didn't happen.

内容的提问来源于stack exchange,提问作者Pierre-Louis LEFEBVRE

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 11:14:04