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

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

私は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」です。

「犬の柱があります」

残念ながら、このような状況を避けることは決して簡単なことではありません。

おすすめ記事