![替換檔案中的單字(區分大小寫)](https://rvso.com/image/169413/%E6%9B%BF%E6%8F%9B%E6%AA%94%E6%A1%88%E4%B8%AD%E7%9A%84%E5%96%AE%E5%AD%97%EF%BC%88%E5%8D%80%E5%88%86%E5%A4%A7%E5%B0%8F%E5%AF%AB%EF%BC%89.png)
我是linux新手,我的檔案中有200行。在該文件中,我需要替換特定的單字,例如:現有單字: foo 新單字: bar
我讀了一些部落格...我知道可以用sed
.但我不知道如何使用 shell 腳本來做到這一點
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”,將變為
“我有一隻狗柱。”
不幸的是,避免這種情況並非完全微不足道。