--- title: 使用 sed 工具針對特定式樣(pattern)的行進行批量搜尋取代操作 description: 更精確地進行純文字資料的搜尋取代,避免操作失誤 tags: sed, search-replace, 搜尋取代, text-manipulation, 純文字資料操作, regular-expression, 正規表達式 lang: zh-tw image: https://i.imgur.com/tXNobFw.png --- # 使用 sed 工具針對特定式樣(pattern)的行進行批量搜尋取代操作 更精確地進行純文字資料的搜尋取代,避免操作失誤 [TOC] ## 使用範例 ### 將所有當前工作目錄中的 HTML 文件中包含 `iframe src` 行的 `com` 字串替換為 `com:12345` 字串 ```shell sed \ --in-place \ '/iframe src/s/com/com:12345/g' \ *.html ``` #### 解說 * `/iframe src/` 為 sed 的正規表達式行地址(regexp line address) * `s/com/com:12345/g` 為 sed 的 s 命令,將比對到的行中全部(`g` 旗標)的 `com` 字串通通替換為 `com:12345` * 因 `/iframe src/s/com/com:12345/g` sed 表達式包含用來斷字(word,Bash 分析命令引數(command argument)的基本單位)的空白字元 metacharacter 故需要用單引號包起來以跳脫(escape)其特殊意義 ## 參考資料 * [Addresses overview (sed, a stream editor)](https://www.gnu.org/software/sed/manual/html_node/Addresses-overview.html#Addresses-overview) * [Regexp Addresses (sed, a stream editor)](https://www.gnu.org/software/sed/manual/html_node/Regexp-Addresses.html#Regexp-Addresses) * [The "s" Command (sed, a stream editor)](https://www.gnu.org/software/sed/manual/html_node/The-_0022s_0022-Command.html#The-_0022s_0022-Command) * [Single Quotes (Bash Reference Manual)](https://www.gnu.org/software/bash/manual/html_node/Single-Quotes.html#Single-Quotes) * [metacharacter - Definitions (Bash Reference Manual)](https://www.gnu.org/software/bash/manual/html_node/Definitions.html#metacharacter) * [word - Definitions (Bash Reference Manual)](https://www.gnu.org/software/bash/manual/html_node/Definitions.html#word) --- 本作品為[《維運猿的共同筆記》](https://hackmd.io/@ops-notes-tw/home)的一部分 頁面連結:<https://hackmd.io/@ops-notes-tw/sed-replace-with-line-address-specifier> 授權條款:<https://hackmd.io/@ops-notes-tw/licensing> 參與協作視同將您的貢獻內容以相同的授權條款釋出