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

如何用Shell的sed/cut/awk命令重命名指定格式的文件

Solution for Removing test or test_ff from Filenames

Got it, let's fix this filename renaming task. You need to strip out either test_ or test_ff_ from your .txt files—here are a few solid approaches tailored to common Unix-like environments:

Most Debian/Ubuntu distros ship with the Perl-based rename tool, which lets you use regex directly for bulk renaming. This is the cleanest option:

# Preview changes first (no actual renaming)
rename -n 's/test(_ff)?_//' *.txt

# If preview looks good, run without -n
rename 's/test(_ff)?_//' *.txt

How it works:

  • The regex test(_ff)?_ matches either test_ (when the (_ff)? group is empty) or test_ff_ (when the group matches _ff).
  • Replacing that match with an empty string removes the unwanted segment entirely.

2. util-linux rename (For RHEL/CentOS-based systems)

If you're on a RHEL/CentOS system, you probably have the util-linux version of rename, which uses a simpler string-replace syntax. Just run these two commands in order (handle the longer pattern first to avoid partial matches):

# First remove test_ff_ to prevent leftover _ff_
rename 'test_ff_' '' *.txt

# Then remove any remaining test_
rename 'test_' '' *.txt

3. sed + mv (If you prefer using sed as you tried earlier)

You can wrap sed in a loop to process each file individually. This works across all Unix-like systems:

# Preview new filenames first
for file in *.txt; do
  echo "$file" → $(echo "$file" | sed -E 's/test(_ff)?_//')
done

# If preview is correct, run the actual rename
for file in *.txt; do
  new_name=$(echo "$file" | sed -E 's/test(_ff)?_//')
  mv "$file" "$new_name"
done

Key Notes:

  • Always use the preview mode first (like -n with Perl rename, or echoing changes in the loop) to avoid accidental data loss.
  • If your filenames contain spaces, make sure to wrap variables in double quotes ("$file", "$new_name") to handle them correctly.
  • To check your rename version, run rename --version—this will tell you which syntax to use.

内容的提问来源于stack exchange,提问作者shaa

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.13 07:34:26