1. 程式人生 > >Linux文本處理命令“sed”簡解

Linux文本處理命令“sed”簡解

linux sed

文本處理編輯命令sed


命令格式:

sed [選項] ‘(截取的行)[動作]‘ 文件名


選項:-n:只把經過sed處理的行輸出

-e:允許輸入多條動作

-i:sed修改的結果寫入文件

截取行:(1)直接輸入行號

(2)/正則表達式/

(3)x,y 從x到y行,也可以用正則取代

(4)x,y! 取反

(5)x~y 從x行開始,步進y行

(6)$ 文檔末

動作:p 打印 eg: sed -n ‘(行)p‘ student.txt

a 行後增加新的一行,i 行前增加新的一行

sed ‘1,5a =============‘ student.txt

sed ‘/正則/a ============‘ student.txt

d 刪除某行

sed ‘/正則/d‘ student.txt

sed ‘4d‘ student.txt

c 替換指定行

sed ‘2c canglaoshi bujigee‘ student.txt

sed ‘/正則/c lalalalalalala‘ student.txt

s 替換指定字符串(替換每行第一個);結尾g表示每一行所有

sed ‘/正則(定位行)/s/正則(舊)/abcd(新)/‘ student.txt

sed ‘s/正則(舊)/abcd(新)/‘ student.txt (全文替換)

sed ‘/www/s/33/000/g‘ zz_test.txt


操作:{}多個命令組合,用;分開

sed ‘{1,20p;s/www/s/33/000//g}‘

& 取原字符

sed ‘s/abc/&def‘ student.txt (把abc換成abcdef)

u 字符串首字母改成大寫

sed ‘s/abc/\u&/‘ student.txt (把abc改成Abc)

l 字符串首字母改成小寫

U 字符串所有字母改成大寫

sed ‘s/abc/\U&/‘ student.txt (把abc改成ABC)

L 字符串所有字母改成小寫

r 將某文件插入到另一文件的指定行中

sed ‘1r abc.txt‘ 123.txt (將abc.txt中的內容插入到123.txt文件的第1行)

q 退出sed

sed ‘/false/q‘ student.txt (找到一個false就退出sed)


本文出自 “sevenot” 博客,轉載請與作者聯系!

Linux文本處理命令“sed”簡解