[[email protected] ~] # sed [選項] '[動作]' 檔名
選項:
[[email protected] ~]# sed '2p' student.txt
ID Name PHP Linux MySQL Average
1 Liming 82 95 86 87.66
1 Liming 82 95 86 87.66
2 Sc 74 96 87 85.66
3 Gao 99 83 93 91.66
[[email protected] ~]# sed -n '2p' student.txt
1 Liming 82 95 86 87.66
[[email protected] ~]#sed '2,4d' student.txt
#刪除從第二行到第四行的資料
ID Name PHP Linux MySQL Average
[[email protected] ~]# cat student.txt
#檔案本身並沒有被修改
ID Name PHP Linux MySQL Average
1 Liming 82 95 86 87.66
2 Sc 74 96 87 85.66
3 Gao 99 83 93 91.66
[[email protected] ~]# sed '2a hello' student.txt
#在第二行後加入hello
ID Name PHP Linux MySQL Average
1 Liming 82 95 86 87.66
hello
2 Sc 74 96 87 85.66
3 Gao 99 83 93 91.66
[[email protected] ~]# sed '2i hello > world' student.txt
#在第二行前插入兩行資料
ID Name PHP Linux MySQL Average
hello
world
1 Liming 82 95 86 87.66
2 Sc 74 96 87 85.66
3 Gao 99 83 93 91.66
[[email protected] ~]# sed -n'2i hello
#只檢視sed命令操作的麵
world' student.txt
hello
world
[[email protected] ~]# cat student.txt | sed '2c No such person'
ID Name PHP Linux MySQL Average
No such person
2 Sc 74 96 87 85.66
3 Gao 99 83 93 91.66
[[email protected] ~]# sed -i'2c No such person' student.txt
[[email protected] ~]# sed's/舊字串/新字串/g' 檔名
替換的格式和 Vim 非常類似,例如:
[[email protected] ~]# sed '3s/74/99/g' student.txt
#在第三行中,把74換成99
ID Name PHP Linux MySQL Average
1 Liming 82 95 86 87.66
2 Sc 99 96 87 85.66
3 Gao 99 83 93 91.66
[[email protected] ~]#sed '4s/^/#/g' student.txt
#在這裡使用正規表示式,"^"代表行首
ID Name PHP Linux MySQL Average
1 Liming 82 95 86 87.66
2 Sc 74 96 87 85.66
#3 Gao 99 83 93 91.66
[[email protected] ~]# sed -e 's/Liming//g; s/Gao//g' student.txt
#同時把"Liming"和"Gao"替換為空
ID Name PHP Linux MySQL Average
1 82 95 86 87.66
2 Sc 74 96 87 85.66
3 99 83 93 91.66
[[email protected] ~]# sed -e 's/Liming//g
> s/Gao//g' student.txt
ID Name PHP Linux MySQL Average
1 82 95 86 87.66
2 Sc 74 96 87 85.66
3 99 83 93 91.66