linux中如何替換檔案中的字串

2021-08-30 17:08:54 字數 1056 閱讀 2903

linux中如何替換檔案中的字串

方法有二:

(一)通過vi編輯器來替換。

vi/vim 中可以使用 :s 命令來替換字串。以前只會使用編輯軟體進行替換,今天發現該命令有很多種寫法(vi 真是強大啊,還有很多需要學習),記錄幾種在此,方便以後查詢。

:s/well/good/ 替換當前行第乙個 well 為 good

:s/well/good/g 替換當前行所有 well 為 good

:n,$s/well/good/ 替換第 n 行開始到最後一行中每一行的第乙個 well 為 good

:n,$s/well/good/g 替換第 n 行開始到最後一行中每一行所有 well 為 good

n 為數字,若 n 為 .,表示從當前行開始到最後一行

:%s/well/good/(等同於 :g/well/s//good/) 替換每一行的第乙個 well 為 good

:%s/well/good/g(等同於 :g/well/s//good/g) 替換每一行中所有 well 為 good

可以使用 # 作為分隔符,此時中間出現的 / 不會作為分隔符

:s#well/#good/# 替換當前行第乙個 well/ 為 good/

:%s#/usr/bin#/bin#g

可以把檔案中所有路徑/usr/bin換成/bin

(二)sumly法直接替換檔案中的字串。(此法不用開啟檔案即可替換字串,而且可以批量替換多個檔案。)

例1

執行命令:

perl -p -i -e "s/china/sumly/g" /www/*.htm /www/*.txt

上面的意思是說將www資料夾下所有的htm和txt檔案中的「china」都替換為「sumly」

例2

執行命令:

perl -p -i -e "s/mry_production/mry_production2/g" ./*.sql

上面的意思是將當前目錄下所有的sql檔案中的「mry_production」替換成「mry_production2」

python替換檔案中的配置值

將文字中的name 配置項值更新為name newvalue import re import os p re.compile r name f file d soft list.txt r f2 file d soft list3.txt w while true line f.readline ...

python替換檔案中的指定內容

編寫的python程式,檔名是file replace.py,具體 如下 usr bin env python coding utf 8 import sys,os if len sys.argv 4 or len sys.argv 5 sys.exit there needs four or fi...

linux下find查詢與批量替換檔案中指定內容

經常在部署tomcat時需要替換配置檔案中的ip,find命令批量替換還是很方便的 查詢需要替換的ip,看看哪些檔案有配置這個ip,執行下面命令 find type f regex xml js.properties xargs grep 118.190.73.218 查詢完成後進行替換為139.1...