如何用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:
- Open a text editor (like Notepad on Windows, TextEdit on macOS, or Gedit on Linux)
- Copy and paste the entire script above into the editor
- Save the file with a name like
replace_abbrevs.sh(make sure the extension is.sh) - Open your terminal/command prompt and navigate to the folder where you saved the script and your .txt files
- Make the script executable by running:
chmod +x replace_abbrevs.sh - Run the script:
./replace_abbrevs.sh
Important Notes:
- Case Insensitivity: The
Iflag insedmakes the search match any case (e.g.,OCTOBER,October,octoberall get replaced withoct). - Whole Words Only: The
\baround 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
sedcommand needs a small tweak—changesed -i''tosed -i ''(add a space between-iand the empty string). Alternatively, if you want to keep backup copies of your original files, usesed -i.bakinstead (this will create files likefile.txt.bakwith 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
相关产品推荐
相关产品推荐

