VIM %s 與 \g ?

最近在學vim遇到一個問題

%s/a/b/g

這行指令會去將整個文檔搜索找到a就替換成b

其中 %s代表全域搜索並取代 , /g表示全域執行
當時我就好奇既然%s有全域的意思那又幹嘛要/g?

開始實驗

原始文件

Image Not Showing Possible Reasons
  • The image file may be corrupted
  • The server hosting the image is unavailable
  • The image path is incorrect
  • The image format is not supported
Learn More →

正常執行

%s /input/in11/g

Image Not Showing Possible Reasons
  • The image file may be corrupted
  • The server hosting the image is unavailable
  • The image path is incorrect
  • The image format is not supported
Learn More →

不加/g執行

%s /input/in11

Image Not Showing Possible Reasons
  • The image file may be corrupted
  • The server hosting the image is unavailable
  • The image path is incorrect
  • The image format is not supported
Learn More →

不執行%s執行/g

Image Not Showing Possible Reasons
  • The image file may be corrupted
  • The server hosting the image is unavailable
  • The image path is incorrect
  • The image format is not supported
Learn More →

OK破案了

%s影響的是搜尋的範圍全域與否
/g影響的是該行取代的行為全域與否

結論

%s不加% , 只會搜尋當前滑鼠該行
/g 不加 , 只會取代掉第一個找到的

tags: vim