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

如何用Shell脚本批量替换文本文件中大小写不敏感的指定字符串

Batch Replace Month/Day Abbreviations in All .txt Files

No worries, I’ll walk you through a simple shell script that does exactly what you need—no prior shell experience required!

Here’s the script you can use:

#!/bin/bash

# Loop through every .txt file in the current directory
for txt_file in *.txt; do
    # Skip if there are no .txt files (avoids errors)
    [ -f "$txt_file" ] || continue

    # Perform case-insensitive replacements:
    # - Replace any case of "october" with "oct"
    # - Replace any case of "november" with "nov"
    # - Replace any case of "monday" with "mon"
    # The \b ensures we only match whole words (not parts of longer words)
    sed -i'' -e 's/\boctober\b/oct/Ig' \
        -e 's/\bnovember\b/nov/Ig' \
        -e 's/\bmonday\b/mon/Ig' \
        "$txt_file"

    echo "Successfully updated: $txt_file"
done

How to use this script:

  1. Open a text editor (like Notepad on Windows, TextEdit on macOS, or Gedit on Linux)
  2. Copy and paste the entire script above into the editor
  3. Save the file with a name like replace_abbrevs.sh (make sure the extension is .sh)
  4. Open your terminal/command prompt and navigate to the folder where you saved the script and your .txt files
  5. Make the script executable by running:
    chmod +x replace_abbrevs.sh
    
  6. Run the script:
    ./replace_abbrevs.sh
    

Important Notes:

  • Case Insensitivity: The I flag in sed makes the search match any case (e.g., OCTOBER, October, october all get replaced with oct).
  • Whole Words Only: The \b around each word ensures we don’t accidentally replace parts of longer words (like if a file had "octoberfest", it won’t turn into "octfest").
  • Cross-Platform Tip: If you’re using macOS, the sed command needs a small tweak—change sed -i'' to sed -i '' (add a space between -i and the empty string). Alternatively, if you want to keep backup copies of your original files, use sed -i.bak instead (this will create files like file.txt.bak with the original content).
  • No .txt Files?: If there are no .txt files in the folder, the script will just skip doing anything—no errors to worry about!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.25 04:12:33