替換檔案中的單字(區分大小寫)

替換檔案中的單字(區分大小寫)

我是linux新手,我的檔案中有200行。在該文件中,我需要替換特定的單字,例如:現有單字: foo 新單字: bar 我讀了一些部落格...我知道可以用sed.但我不知道如何使用 shell 腳本來做到這一點

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”,將變為

“我有一隻狗柱。”

不幸的是,避免這種情況並非完全微不足道。

相關內容