sed命令

sed是一種包括在所有unix平臺(包括Linux)的輕量級編輯器。sed主要是用來將數據進行選取,替換,刪除,新增的命令。

功能:字符串替換命令

格式:sed [選項] ‘[動作]’ 文件名

選項:

-n:一般sed命令會把所有數據都輸出到屏幕,如果加入此選擇,則只會把經過sed命令處理的行輸出到屏幕。不會修改文件的原始內容,只會將顯示到屏幕
-e:允許對輸入數據應用多條sed命令編輯
-i:用sed的修改結果直接修改讀取數據的文件,而不是由屏幕輸出

動作:

a:追加,在當前行後添加一行或多行
c:行替換,用c後面的字符串替換原數據行
i:插入,在當期行前插入一行或多行。
d:刪除,刪除指定的行
p:打印,輸出指定的行。
s:字符串替換,用一個字符串替換另外一個字符串。格式爲“行範圍s/舊字符串/新字符串/g”(和vim中的替換格式類似)

示例:行數據操作

打印第二行,一定添加-n,如果不加-n會把所有內容輸出,並且會出現重複行。

[root@localhost home]# sed '2p' student.txt 
ID  Name    gender  Mark
1   furong  F   88
1   furong  F   88
2   fengjie F   60
3   cang    F   70
[root@localhost home]# sed -n '2p' student.txt 
1   furong  F   88
[root@localhost home]# 

刪除

[root@localhost home]# cat student.txt 
ID  Name    gender  Mark
1   furong  F   88
2   fengjie F   60
3   cang    F   70
[root@localhost home]# sed '2d' student.txt 
ID  Name    gender  Mark
2   fengjie F   60
3   cang    F   70
[root@localhost home]# sed '2,4d' student.txt //刪除2-4行
ID  Name    gender  Mark
[root@localhost home]# sed '2d' student.txt 
ID  Name    gender  Mark
2   fengjie F   60
3   cang    F   70
[root@localhost home]# sed '2,4d' student.txt 
ID  Name    gender  Mark
[root@localhost home]# sed '2a piaoliang jiushi renxing' student.txt 
ID  Name    gender  Mark
1   furong  F   88
piaoliang jiushi renxing
2   fengjie F   60
3   cang    F   70
[root@localhost home]# sed '2i piaoliang jiushi renxing' student.txt 
ID  Name    gender  Mark
piaoliang jiushi renxing
1   furong  F   88
2   fengjie F   60
3   cang    F   70
[root@localhost home]# cat student.txt 
ID  Name    gender  Mark
1   furong  F   88
2   fengjie F   60
3   cang    F   70
[root@localhost home]# 
[root@localhost home]# cat student.txt 
ID  Name    gender  Mark
1   furong  F   88
2   fengjie F   60
3   cang    F   70
[root@localhost home]# sed '4c cang bujige' student.txt 
ID  Name    gender  Mark
1   furong  F   88
2   fengjie F   60
cang bujige
[root@localhost home]# cat student.txt 
ID  Name    gender  Mark
1   furong  F   88
2   fengjie F   60
3   cang    F   70
[root@localhost home]# sed '4s/70/100/g' student.txt 
ID  Name    gender  Mark
1   furong  F   88
2   fengjie F   60
3   cang    F   100
[root@localhost home]# sed -i '4s/70/100/g' student.txt 
[root@localhost home]# cat student.txt 
ID  Name    gender  Mark
1   furong  F   88
2   fengjie F   60
3   cang    F   100
[root@localhost home]# sed -e 's/furong//g;s/fengj//g' student.txt 
ID  Name    gender  Mark
1       F   88
2   ie  F   60
3   cang    F   100
發佈了81 篇原創文章 · 獲贊 19 · 訪問量 35萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章