![大きなファイル内の文字列を置き換えるにはどうすればいいですか?](https://rvso.com/image/1048330/%E5%A4%A7%E3%81%8D%E3%81%AA%E3%83%95%E3%82%A1%E3%82%A4%E3%83%AB%E5%86%85%E3%81%AE%E6%96%87%E5%AD%97%E5%88%97%E3%82%92%E7%BD%AE%E3%81%8D%E6%8F%9B%E3%81%88%E3%82%8B%E3%81%AB%E3%81%AF%E3%81%A9%E3%81%86%E3%81%99%E3%82%8C%E3%81%B0%E3%81%84%E3%81%84%E3%81%A7%E3%81%99%E3%81%8B%3F%20.png)
私の Ubuntu サーバーには、約 7 GB の大きな WordPress SQL ダンプ ファイルがあります。ドメインを変更するので、ファイル内のドメイン名を置き換える必要があります。コマンド ラインでこれを行う方法を知りたいです。
dev.example.com
交換する必要がある
example.com
答え1
インプレース編集でsedを使用することができます
sed -i -e 's/dev\.example\.com/example\.com/g' filename
答え2
タグがどの程度厳密であるかはわかりませんがsed
、ファイル内の文字列をコマンドで置き換える普遍的な方法は次のとおりです。
<script> <file> <old_string> <new_string>
以下の小さな Python スクリプトを使用できます。
#!/usr/bin/env python3
import sys
file = sys.argv[1]; old_string = sys.argv[2]; new_string = sys.argv[3]
with open(file) as src:
lines = src.read()
print(lines.replace(old_string, new_string))
スクリプトを空のファイルにコピーし、replace.py
実行可能ファイルとして保存し(プレフィックスなしで実行するpython3
)、次のコマンドで実行します。
/path/to/replace.py /path/to/file dev.example.com example.com
old_string または new_string のいずれかにスペースが含まれている場合は、引用符を使用します。
/path/to/replace.py /path/to/file 'old string with spaces' 'new string with spaces'