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

如何在Bash脚本中实现文件名按指定长度截断功能?

Implement Filename Truncation in Your Bash Script

Alright, let's get that filename truncation feature working for option 3 of your script. The core goal is to split each filename into its base name and extension, truncate the base to your specified length, then stitch them back together. Here's a robust implementation you can drop right into your existing framework:

Step 1: Add the Truncation Logic to Option 3

In your script's case statement where option 3 is handled, replace the placeholder with this code:

3)
    read -p "Enter the desired truncation length: " trunc_len
    # Validate input is a positive integer (no zeros or non-numeric values)
    if ! [[ "$trunc_len" =~ ^[1-9][0-9]*$ ]]; then
        echo "Error: Please enter a valid positive integer."
        break
    fi

    # Loop through all regular files in the current directory (skip folders)
    for file in *; do
        if [[ -f "$file" ]]; then
            # Split filename into base name and extension
            base_name="${file%.*}"
            file_ext="${file##*.}"

            # Handle files with no extension
            if [[ "$base_name" == "$file" ]]; then
                new_filename="${base_name:0:$trunc_len}"
            else
                new_filename="${base_name:0:$trunc_len}.$file_ext"
            fi

            # Skip renaming if the truncated name matches the original
            if [[ "$new_filename" != "$file" ]]; then
                # Optional: Avoid overwriting existing files with duplicate truncated names
                counter=1
                temp_name="$new_filename"
                while [[ -e "$temp_name" ]]; do
                    temp_name="${base_name:0:$trunc_len}_$counter.$file_ext"
                    ((counter++))
                done
                mv -v "$file" "$temp_name"
            fi
        fi
    done
    echo "Filename truncation completed successfully!"
    ;;

Step 2: Breakdown of the Key Logic

Let's walk through what each part does to make sure you understand:

  • Input Validation: We check that the user enters a positive integer to prevent invalid truncation lengths (like 0 or letters).
  • File Filtering: The -f "$file" check ensures we only modify regular files, not directories or symlinks.
  • Splitting Filenames:
    • ${file%.*} removes the shortest suffix starting with . to get the base name (e.g., Adsbgnyr.txt → Adsbgnyr).
    • ${file##*.} removes the longest prefix ending with . to get the extension (e.g., Adsbgnyr.txt → txt).
  • No-Extension Handling: If the base name matches the original file, that means there's no extension—we just truncate the full name directly.
  • Duplicate Protection: The counter adds a suffix (like _1, _2) if multiple files truncate to the same name, so you don't accidentally overwrite existing files.

Step 3: Test It Out

Create a few test files to verify the functionality:

touch Adsbgnyr.txt HelloWorld.pdf MySuperLongFilename NoExtensionTest

Run your script, select option 3, enter 3, and you'll see:

  • Adsbgnyr.txt → Ads.txt
  • HelloWorld.pdf → Hel.pdf
  • MySuperLongFilename → MyS
  • NoExtensionTest → NoE

This implementation is flexible, handles edge cases, and integrates seamlessly with your existing script structure.

内容的提问来源于stack exchange,提问作者Max The Not So Smart

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.09 21:27:44