LinuxのBashスクリプトを使用して複数のファイルにテキストを置き換える方法
If you have many files with outdated information, updating them manually is time-consuming. Whether it's fixing outdated file paths, renaming variables, or modifying config values, Bash provides powerful tools like grep, sed, and find to automate this task. In this guide, we will learn how to replace text across multiple files efficiently using a Bash script.
Table of Contents
Why and When Use Bash for Bulk Text Replacement?
Automating text replacement is useful for:
- Updating variable names in code files.
- Changing file paths in scripts.
- Fixing incorrect configuration settings.
- Renaming project names in documentation.
Instead of editing each file manually, a Bash script can do it in seconds.
Allow me to explain it with an example Bash script.
Problem: Bulk Replace Paths in Multiple Files
Imagine you have multiple files referring to old log file paths:
- Old Path: ~/data/logs/app.log
- New Path: ~/data/log/app.log
Instead of searching and replacing each instance manually, let’s automate it.
Step 1: Create a Test Directory and Sample Files
First, create a test environment before modifying real files.
Create a directory in your home folder:
mkdir -p ~/replace_test && cd ~/replace_test
Create sample files containing the old path:
echo 'Log file: ~/data/logs/app.log' > script1.sh echo 'ERROR_LOG="~/data/logs/app.log"' > config.env echo 'echo "Processing ~/data/logs/app.log"' > process.sh
Verify occurrences of the old path:
grep "~/data/logs/app.log" *
Sample Output:
config.env:ERROR_LOG="~/data/logs/app.log" process.sh:echo "Processing ~/data/logs/app.log" script1.sh:Log file: ~/data/logs/app.log
Step 2: Replace Text in Multiple Files Using a Bash Script
Now, create a script named replace_text.sh:
#!/usr/bin/env bashif [[ $# -ne 3 ]]; then echo "Usage: $0 <old_path> <new_path> <directory>" exit 1fiOLD_PATH=$(printf '%s\n' "$1" | sed 's/[\/&]/\\&/g')NEW_PATH=$(printf '%s\n' "$2" | sed 's/[\/&]/\\&/g')SEARCH_DIR=$3echo "Replacing occurrences of: $1 -> $2 in $SEARCH_DIR"# Find and replace text safelyfind "$SEARCH_DIR" -type f -exec sed -i "s/$OLD_PATH/$NEW_PATH/g" {} +echo "Replacement completed."
Step 3: Make the Script Executable
chmod +x replace_text.sh
Step 4: Run the Script
Execute the script to replace all occurrences of ~/data/logs/app.log with ~/data/log/app.log:
./replace_text.sh "~/data/logs/app.log" "~/data/log/app.log" ~/replace_test
Sample Output:
Replacing occurrences of: ~/data/logs/app.log -> ~/data/log/app.log in /home/ostechnix/replace_test Replacement completed.
Step 5: Verify the Changes
Run:
grep "~/data/log/app.log" *
Sample Output:
config.env:ERROR_LOG="~/data/log/app.log" process.sh:echo "Processing ~/data/log/app.log" script1.sh:Log file: ~/data/log/app.log
Ensure no old path remains:
grep "~/data/logs/app.log" *
If there's no output, the replacement worked.
This script,
- Handles Special Characters: Escapes /, &, and other symbols correctly.
- Uses find -exec sed: Safer than grep | xargs sed.
- Efficient for Large Projects: Works on many files without excessive CPU usage.
You can now use this script on real files.
Precautions Before Running it on Real Files:
- Backup Your Files: Always create a backup before making bulk changes
- Test on a Small Sample: Run it on a test directory first, as we did with ~/replace_test.
- Dry Run with grep: Check how many files will be affected. You can run grep -rl "~/data/logs/app.log" ~/replace_test/ to do it.
- Manually Inspect Changes: After running the script, verify a few modified files.
Conclusion
In this tutorial, we learned how to replace text in multiple files using a simple Bash script. We have explained how this script automates path updates in multiple files, preventing errors and saving time with a practical example. Always test with backups before running on critical files.
Related Read:
- Bash Shell Scripting Tutorial For Beginners
以上がLinuxのBashスクリプトを使用して複数のファイルにテキストを置き換える方法の詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

ホットAIツール

Undresser.AI Undress
リアルなヌード写真を作成する AI 搭載アプリ

AI Clothes Remover
写真から衣服を削除するオンライン AI ツール。

Undress AI Tool
脱衣画像を無料で

Clothoff.io
AI衣類リムーバー

Video Face Swap
完全無料の AI 顔交換ツールを使用して、あらゆるビデオの顔を簡単に交換できます。

人気の記事

ホットツール

メモ帳++7.3.1
使いやすく無料のコードエディター

SublimeText3 中国語版
中国語版、とても使いやすい

ゼンドスタジオ 13.0.1
強力な PHP 統合開発環境

ドリームウィーバー CS6
ビジュアル Web 開発ツール

SublimeText3 Mac版
神レベルのコード編集ソフト(SublimeText3)

ホットトピック











インターネットは単一のオペレーティングシステムに依存していませんが、Linuxはその上で重要な役割を果たしています。 Linuxは、サーバーやネットワークデバイスで広く使用されており、安定性、セキュリティ、スケーラビリティに人気があります。

Linux管理者の平均年salは、米国で75,000〜95,000ドル、ヨーロッパでは40,000〜60,000ユーロです。給与を増やすには、次のことができます。1。クラウドコンピューティングやコンテナテクノロジーなどの新しいテクノロジーを継続的に学習します。 2。プロジェクトの経験を蓄積し、ポートフォリオを確立します。 3.プロフェッショナルネットワークを確立し、ネットワークを拡大します。

Linuxシステム管理者の主なタスクには、システムの監視とパフォーマンスチューニング、ユーザー管理、ソフトウェアパッケージ管理、セキュリティ管理とバックアップ、トラブルシューティングと解像度、パフォーマンスの最適化、ベストプラクティスが含まれます。 1. TOP、HTOP、その他のツールを使用して、システムのパフォーマンスを監視し、チューニングします。 2。ユーザーADDコマンドおよびその他のコマンドを介して、ユーザーアカウントとアクセス許可を管理します。 3. APTとYUMを使用してソフトウェアパッケージを管理し、システムの更新とセキュリティを確保します。 4.ファイアウォールを構成し、ログを監視し、データバックアップを実行して、システムセキュリティを確保します。 5.ログ分析とツールの使用を通じてトラブルシューティングと解決。 6.カーネルパラメーターとアプリケーションの構成を最適化し、ベストプラクティスに従ってシステムのパフォーマンスと安定性を向上させます。

Linuxの主な用途には、1。Serverオペレーティングシステム、2。EmbeddedSystem、3。Desktopオペレーティングシステム、4。開発およびテスト環境。 Linuxはこれらの分野で優れており、安定性、セキュリティ、効率的な開発ツールを提供します。

仮想化サポートのLinuxとWindowsの主な違いは次のとおりです。1)LinuxはKVMとXenを提供し、優れたパフォーマンスと柔軟性を備えており、高いカスタマイズ環境に適しています。 2)Windowsは、友好的なインターフェイスを備えたHyper-Vを介した仮想化をサポートし、Microsoftソフトウェアに依存する企業に適したMicrosoft Ecosystemと密接に統合されています。

Linuxの学習は難しくありません。 1.Linuxは、UNIXに基づいたオープンソースオペレーティングシステムであり、サーバー、組み込みシステム、およびパーソナルコンピューターで広く使用されています。 2。ファイルシステムと許可管理を理解することが重要です。ファイルシステムは階層的であり、許可には読み取り、書き込み、実行が含まれます。 3。APTやDNFなどのパッケージ管理システムは、ソフトウェア管理を便利にします。 4。プロセス管理は、PSおよびTOPコマンドを通じて実装されます。 5. MKDIR、CD、Touch、Nanoなどの基本的なコマンドから学習を開始し、シェルスクリプトやテキスト処理などの高度な使用法を試してください。 6.許可問題などの一般的なエラーは、SudoとChmodを通じて解決できます。 7.パフォーマンスの最適化の提案には、HTOPを使用してリソースを監視すること、不要なファイルのクリーニング、SYの使用が含まれます

Linuxソフトウェア分布は、各分布のエコシステムに深く染み込んでおり、DEBやRPMなどのネイティブ形式に依存していました。 ただし、フラットパックとスナップが出現し、アプリケーションパッケージへの普遍的なアプローチが約束されています。 この記事試験

このガイドでは、システム管理者と開発者にとって重要なタスクであるLinuxのテキストファイルを比較するためのさまざまな方法を調査します。 コマンドラインツールと視覚的なDIFFツールをカバーし、その強みと適切なユースケースを強調します。 仮定しましょう
