如何用Shell的sed/cut/awk命令重命名指定格式的文件
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:
1. Perl-style rename (Recommended for Debian/Ubuntu-based systems)
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 eithertest_(when the(_ff)?group is empty) ortest_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
-nwith 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
renameversion, runrename --version—this will tell you which syntax to use.
内容的提问来源于stack exchange,提问作者shaa

