如何唯一识别文件名?地址流文件分类存储的技术问询
Hey there! Let's work through this filename sorting challenge you're facing. Since you can't rename files within the job and need to split filenames into two groups—those without _1 and those that include it—here are a couple of practical, platform-friendly solutions:
Shell Script (Bash)
If you're working in a Unix-like environment (Linux, macOS, WSL on Windows), a bash script is quick and straightforward:
First, set up your output files and clear any old content:
> no_1_files.txt > with_1_files.txtThen loop through all files, filter out directories, and sort filenames into the right lists:
for file in *; do if [[ -f "$file" ]]; then # Check if the filename contains "_1" if [[ "$file" == *"_1"* ]]; then echo "$file" >> with_1_files.txt else echo "$file" >> no_1_files.txt fi fi done- Need to match filenames that end with
_1(e.g.,invoice_1instead ofinvoice_1_draft)? Adjust the condition to[[ "$file" == *_1 ]]. - Want to target specific file types? Swap
*for something like*.pdfor*.docx.
- Need to match filenames that end with
Python Script (Cross-Platform)
For a solution that works across Windows, macOS, and Linux, Python is a solid choice—especially if you need more flexibility later:
import os # Set your target directory (use '.' for current folder) target_directory = "." # Define output file names no_suffix_file = "no_1_files.txt" with_suffix_file = "with_1_files.txt" # Write filenames to the correct files with open(no_suffix_file, "w") as no_1, open(with_suffix_file, "w") as with_1: for filename in os.listdir(target_directory): full_path = os.path.join(target_directory, filename) # Only process actual files, skip directories if os.path.isfile(full_path): if "_1" in filename: with_1.write(f"{filename}\n") else: no_1.write(f"{filename}\n")
Run this script, and you’ll get two clean text files with your sorted filenames.
Quick Tips
- Both methods handle filenames with spaces, special characters, and weird symbols—no need to worry about breaking things.
- Since we’re only reading and recording filenames (not modifying the actual files), this won’t interfere with your existing mailing/physical file error issues.
- If you need to scan subdirectories too, let me know—I can tweak the scripts to add recursive support!
内容的提问来源于stack exchange,提问作者user276024

