﻿# 使用 sed 工具在 Linux 環境下快速完成「搜尋取代」的任務

在 Windows 有 [grepWin](https://tools.stefankueng.com/grepWin.html) 可快速執行多檔案的搜尋取代任務，而在 Linux 環境下就非 [sed](http://en.wikipedia.org/wiki/Sed) 莫屬了，為了能讓 [sed](http://en.wikipedia.org/wiki/Sed) 的功效達到極致，你還需要多瞭解 [find](http://en.wikipedia.org/wiki/Find) 指令與 [Regular expression](http://en.wikipedia.org/wiki/Regex) 語法才能對你的搜尋取代任務更靈活的運用，以下是幾個常用的指令與說明。

**學習** [**sed**](http://en.wikipedia.org/wiki/Sed) **的流程：**

1.  先練習單一檔案操作，並練習搜尋取代的語法 (不直接寫入檔案)
2.  確認語法正確後，就可以套用 **\-i** 選項參數可將搜尋取代的結果直接寫入該檔案
3.  確認無誤後可搭配 [find](http://en.wikipedia.org/wiki/Find) 指令進行多檔案批次搜尋取代 (功能強大、威力十足)

**使用** [**sed**](http://en.wikipedia.org/wiki/Sed) **的範例：**

1\. 針對單一檔案進行搜尋取代 ( 針對每一行**第一次出現**的搜尋文字 ) ( 區分大小寫 )

```
sed -e 's/cpu/memory/' test.txt
```

   備註 1：如上例 **cpu** 為搜尋字串，而 **memory** 為替代字串，而替代的結果會直接輸出在畫面上。  
   備註 2：此範例並沒有加上 **\-i** 選項參數，所以替代的結果並不會寫入 **test.txt** 檔案。

2\. 針對單一檔案進行搜尋取代 ( 針對每一行**第一次出現**的搜尋文字 ) ( **不區分大小寫** )

```
sed -e 's/cpu/memory/i' test.txt
```

3\. 針對單一檔案進行搜尋取代 ( 針對每一行**所有出現過**的搜尋文字 ) ( **不區分大小寫** )

```
sed -e 's/cpu/memory/gi' test.txt
```

4\. 針對單一檔案進行搜尋取代 ( 針對每一行**第一次出現**的搜尋文字 ) ( 將搜尋取代的結果直接回寫檔案 )

```
sed -i -e 's/cpu/memory/i' test.txt
```

5\. 利用 [find](http://en.wikipedia.org/wiki/Find) 指令找到多個符合條件的檔案，並使用 [sed](http://en.wikipedia.org/wiki/Sed) 做搜尋取代的動作

```
find . -type f -exec sed -e 's/cpu/memory/ig' '{}' \;
```

   注意：使用 [find](http://en.wikipedia.org/wiki/Find) 指令搭配 **\-exec** 參數時，最後一個 **\\;** 是非常重要的關鍵，一定要加上才能正常執行。

**相關連結**

-   [sed - Wikipedia, the free encyclopedia](http://en.wikipedia.org/wiki/Sed)
-   [find - Wikipedia, the free encyclopedia](http://en.wikipedia.org/wiki/Find)
-   [Regular expression - Wikipedia, the free encyclopedia](http://en.wikipedia.org/wiki/Regex)
-   [鳥哥的 Linux 私房菜 -- 正規表示法 (regular expression, RE) 與文件格式化處理](https://linux.vbird.org/linux_basic/centos7/0330regularex.php)
-   [FIND AND REPLACE with SED](http://www.brunolinux.com/02-The_Terminal/Find_and%20Replace_with_Sed.html)
-   [Common threads: Sed by example, Part 1](http://www.ibm.com/developerworks/linux/library/l-sed1.html)
-   [Common threads: Sed by example, Part 2](http://www.ibm.com/developerworks/linux/library/l-sed2.html)
-   [Common threads: Sed by example, Part 3](http://www.ibm.com/developerworks/linux/library/l-sed3.html)
-   [Common threads: Awk by example, Part 1](http://www.ibm.com/developerworks/library/l-awk1.html)
-   [Common threads: Awk by example, Part 2](http://www.ibm.com/developerworks/library/l-awk2.html)
-   [Common threads: Awk by example, Part 3](http://www.ibm.com/developerworks/library/l-awk3.html)
-   [regular expression - How can I use sed to replace a multi-line string? - Unix & Linux Stack Exchange](https://unix.stackexchange.com/a/525524/288400)
