![ファイル内の単語(大文字と小文字を区別)を置換する](https://rvso.com/image/169413/%E3%83%95%E3%82%A1%E3%82%A4%E3%83%AB%E5%86%85%E3%81%AE%E5%8D%98%E8%AA%9E%EF%BC%88%E5%A4%A7%E6%96%87%E5%AD%97%E3%81%A8%E5%B0%8F%E6%96%87%E5%AD%97%E3%82%92%E5%8C%BA%E5%88%A5%EF%BC%89%E3%82%92%E7%BD%AE%E6%8F%9B%E3%81%99%E3%82%8B.png)
私は Linux 初心者で、ファイルに 200 行あります。そのファイルで、特定の単語を置き換える必要があります。例:既存の単語: foo 新しい単語: bar
いくつかのブログを読んで、それができることは理解しましたsed
。しかし、シェルスクリプトでそれを実行する方法がわかりません。
sed 's/foo/bar/' /path to a file
スクリプトを書く必要がありますが、ファイルを入力として渡す方法や、変数に保存して特定の単語を変更する方法がわかりません。
スクリプトは、ファイル名だけでなく特定の単語も変更する必要があります。例: 入力ファイル名: cat home.txt (置換する単語 -->cat) 出力ファイル名: Dog home.txt (Cat を Dog に置換)
どうか助けてください!
答え1
文字列を変更したい場合は、foo
次bar
のようにします。
#!/bin/bash
# the pattern we want to search for
search="foo"
# the pattern we want to replace our search pattern with
replace="bar"
# my file
my_file="/path/to/file"
# generate a new file name if our search-pattern is contained in the filename
my_new_file="$(echo ${my_file} | sed "s/${search}/${replace}/")"
# replace all occurrences of our search pattern with the replace pattern
sed -i "s/${search}/${replace}/g" "${my_file}"
# rename the file to the new filename
mv "${my_file}" "${my_new_file}"
検索パターンが単語の一部と一致する場合、その部分も置換されることに注意してください。例:
「芋虫がいます。」
検索文字列が「cat」で置換文字列が「dog」の場合、次のようになります。
「私はイヌタデを飼っています。」
残念ながら、これを避けるのは簡単ではありません。