# 使用 Regex 正則表達式對資料夾中的文字檔進行搜尋與取代的三種作法

在整理開發環境的時候，經常會有批次調整檔案內容的需求，我今天特別整理了 3 種不同的解決方案，這些方法都可以看情況使用！

![man sed](https://stwillblogassets.blob.core.windows.net/files/images/external/user-images.githubusercontent.com/acda14003b90e7a087b8-216257841-d135e9c5-a9cc-438f-80e7-e95a79c626fc.jpg)

-   Linux / WSL
    
    在 Linux 環境下使用 `find` 與 `sed` 幾乎是標準方案，這套組合拳確實快速又強大！👍
    
    ```bash
    find src -name '*.ts' -type f -exec sed -i 's/pattern\([s]\)/replacement\1/g' '{}' \;
    ```
    
    透過 `sed` 來取代內容的話，在 `Regex` 語法上稍微有點不同，左邊的小括弧要加上反斜線跳脫 ( `\(` 或 `\)` )，而 backreference 也要用反斜線來表達 ( `\1`, `\2`, ... )
    
-   PowerShell
    
    在 Windows 上面使用 PowerShell 來寫腳本，可讀性會比較好！
    
    ```powershell
    Get-ChildItem -Path 'src' -Include '*.ts' -Recurse -Exclude reparsepoint | ForEach-Object {
      $current_file = "$($_.FullName)"
      $replace_file = "$($_.FullName).new"
    
      # 這裡 Get-Content 前後的小括弧很重要，一定要加上才能得到 String 的結果，指定 utf8 編碼也十分重要！
      (Get-Content -LiteralPath $current_file -Encoding utf8) -replace 'pattern([s])', 'replacement$1' |
        Out-File -Encoding utf8 -LiteralPath $replace_file
    
      Move-Item -LiteralPath $replace_file -Destination $current_file -Force
    }
    ```
    
-   Node.js
    
    如果我們要在前端專案中整合字串取代的工作，在 `package.json` 的 `scripts` 直接取代檔案，同時又要兼顧**跨平台**的話，採用既有的 npm 套件就會來的方便許多。這裡我找了個 [replace-in-file](https://www.npmjs.com/package/replace-in-file) 套件還不錯！👍
    
    先安裝到專案中：
    
    ```batch
    npm install -D replace-in-file
    ```
    
    取代內容可以這樣寫，也可以使用超好用的 Glob 語法(e.g. `src/**/*.ts`)：
    
    ```batch
    npx replace-in-file "/pattern([s])/g" "replacement$1" src/**/*.ts --isRegex --encoding=utf-8
    ```
    

### 相關連結

-   [sed(1) - Linux manual page](https://man7.org/linux/man-pages/man1/sed.1.html)
    -   [Linux 以 sed 指令搜尋、取代檔案內容教學與範例](https://blog.gtwang.org/linux/linux-sed-find-and-replace-text-in-file-tutorial-examples/)
-   [replace-in-file - npm](https://www.npmjs.com/package/replace-in-file)
    -   GitHub: [https://github.com/adamreisnz/replace-in-file](https://github.com/adamreisnz/replace-in-file)
