0

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

 1 year ago
source link: https://blog.miniasp.com/post/2023/02/02/How-to-search-and-replace-using-regex-in-3-ways
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

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

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

man sed
  • Linux / WSL

    在 Linux 環境下使用 findsed 幾乎是標準方案,這套組合拳確實快速又強大!👍

    find src -name '*.ts' -type f -exec sed -i 's/pattern\([s]\)/replacement\1/g' '{}' \;
    

    透過 sed 來取代內容的話,在 Regex 語法上稍微有點不同,左邊的小括弧要加上反斜線跳脫 ( \(\) ),而 backreference 也要用反斜線來表達 ( \1, \2, ... )

  • PowerShell

    在 Windows 上面使用 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.jsonscripts 直接取代檔案,同時又要兼顧跨平台的話,採用既有的 npm 套件就會來的方便許多。這裡我找了個 replace-in-file 套件還不錯!👍

    先安裝到專案中:

    npm install -D replace-in-file
    

    取代內容可以這樣寫,也可以使用超好用的 Glob 語法(e.g. src/**/*.ts):

    npx replace-in-file "/pattern([s])/g" "replacement$1" src/**/*.ts --isRegex --encoding=utf-8
    

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK