sed直接替換檔案內容

2021-06-16 09:08:02 字數 743 閱讀 1227

sed -i "s/zhangsan/lisi/g" `grep zhangsan -rl /modules`

解釋一下:

-i 表示inplace edit,就地修改檔案

-r 表示搜尋子目錄

-l 表示輸出匹配的檔名

這個命令組合很強大,要注意備份檔案。

(1)sed 'y/1234567890/abcdefghij/' test_sed

sed 'y/1234567890/abcdefghij/' filename

abcdefghij

bcdefghija

cdefghijab

defghijabc

注意變換關係是按兩個list的位置對應變換

其中:test_sed的內容是:

1234567890

2345678901

3456789012

4567890123

(2)替換每行所有匹配

sed 's/01/ab/g' test_sed

1234567890

23456789ab

3456789ab2

456789ab23

注意:第一行的0,1沒有分別替換為a,b

$ sed '/test/i\\

new line

-------------------------' example

如果test被匹配,則把反斜槓後面的文字插入到匹配行的前面。

sed直接替換檔案內容

sed i s zhangsan lisi g grep zhangsan rl modules 解釋一下 i 表示inplace edit,就地修改檔案 r 表示搜尋子目錄 l 表示輸出匹配的檔名 這個命令組合很強大,要注意備份檔案。1 sed y 1234567890 abcdefghij te...

sed直接替換檔案內容

sed i s zhangsan lisi g grep zhangsan rl modules 解釋一下 i 表示inplace edit,就地修改檔案 r 表示搜尋子目錄 l 表示輸出匹配的檔名 這個命令組合很強大,要注意備份檔案。1 sed y 1234567890 abcdefghij te...

替換檔案內容

前幾天無意間看見一道題,內容大致是這樣的。有乙個檔案,裡面內容是這樣的格式 1 aa 2 bb 3 cc 4 dd 現在想插入3 ee,如果存在3 那麼把後面內容換成新內容,如果不存在則新增一行。一開始我是這麼寫的 後來經指點使用字典可以這麼寫 tmp with open 1 r as fd a f...