ファイル内の単語(大文字と小文字を区別)を置換する

ファイル内の単語(大文字と小文字を区別)を置換する

私は Linux 初心者で、ファイルに 200 行あります。そのファイルで、特定の単語を置き換える必要があります。例:既存の単語: foo 新しい単語: bar いくつかのブログを読んで、それができることは理解しましたsed。しかし、シェルスクリプトでそれを実行する方法がわかりません。

sed 's/foo/bar/' /path to a file

スクリプトを書く必要がありますが、ファイルを入力として渡す方法や、変数に保存して特定の単語を変更する方法がわかりません。

スクリプトは、ファイル名だけでなく特定の単語も変更する必要があります。例: 入力ファイル名: cat home.txt (置換する単語 -->cat) 出力ファイル名: Dog home.txt (Cat を Dog に置換)

どうか助けてください!

答え1

文字列を変更したい場合は、foobarのようにします。

#!/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」の場合、次のようになります。

「私はイヌタデを飼っています。」

残念ながら、これを避けるのは簡単ではありません。

関連情報