1. 程式人生 > >sed用法

sed用法

正則 操作 用法 輸入 保存到文件 pass 需要 文件file 結果

參數

-i # 將修改保存到文件
-e # 在命令行運行多條sed命令
-n # 打印由p命令指定的行
-f # 指定sed命令腳本文件
-r #使用擴展正則表達式,脫意

替換標記,4種可用的替換標記
s/pattern/replacement/flags
數字,替換一行中第幾次模式匹配的地方
g 替換一行中所有匹配的地方
p 打印匹配的行
w file ,將替換結果寫到文件file中,只寫匹配的內容
數字尋址,用數字來指定行

#-i 參數的一個用法
sed -i.bak ‘s/bin/sbin/g‘ /etc/passwd
#此命令會在修改文件前備份,並以.bak為後綴

匹配行:

  1. sed -n ‘2,5p‘ /etc/passwd # 打印2-5行
  2. sed ‘1,10d‘ /etc/passwd # 刪除1-10行
    #最後一行可以用 $ 表示,例如3,$表示從第三行到最後一行
    #addr1,+N # 表示 從addr1到addr1+N行,例如2,8,表示2-10行
    #addr1,~N # 表示從addr1到N的倍數的行,例如5,~4 ,表示5-8行,因為8是大於5的4的整數倍的最小一個
    #first~step # 表示以first開始,後面每次加step,例如1~2,表示所有的奇數行,如下所示

替換

  1. sed -n ‘s/pattern/replace/‘ /etc/passwd # 替換首次匹配的pattern為replace
  2. sed -n ‘s/pattern/replace/g‘ /etc/passwd # 替換所有,g表示全局
  3. sed -n ‘s/pattern/&replace/g‘ file # 在pattern後增加
  4. sed -n ‘s/pattern/replace&/g‘ file # 在pattern前增加
  5. sed -n ‘s/pattern/\L&/g‘ file # 將pattern轉換為大寫
  6. sed -n ‘s/pattern/\U&/g‘ file # 將pattern轉換為小寫
  7. sed -n ‘s/[A-Z]/\l&/g‘ file # 將文件中的大寫字母轉換為小寫,\l,\u只支持單個字符,\L,\U支持多個,\b大家應該知道是錨定的意思,說白了就是邊界符,那麽這就只會匹配第一個開頭的字母,然後\U的意思在元字符裏的解釋是“大寫(不是標題首字符)\E 以前的字符”,而\u只是將下一個字符變為大寫,註意它們的區別噢。

刪除

#註意,d命令是在後面的,s命令在前面

  1. sed 1,5d file # 刪除1-5行
  2. sed ‘/pattern/d‘ # 刪除匹配的行
    #刪除操作的匹配模式跟替換一樣
  3. sed ‘s/[0-9]//g‘ 1.txt #刪除所有數字
  4. sed ‘s/[^0-9]//g‘ 1.txt #刪除所有非數字

插入

#在行後插入

  1. sed 1,4G file # 在1-4行後面插入一行空行
  2. sed ‘/pattern/G‘ # 在匹配行後面插入一個空行
  3. sed G file # 在每一行後面插入一個空行
  4. sed ‘s/$/wq&/‘ file # 在行尾插入字符wq
  5. sed ‘/pattern/a\new line‘ file # 在匹配行後插入一行new line,匹配模式可以是正則表達式,也可以是行地址
    #在行前插入
  6. sed 1,4‘{x;p;x}‘ file # 在1-4行前插入一個空行,註意與G的不同
  7. sed N‘{x;p;x}‘ # 在第N行前插入空行
  8. sed ‘/root/{x;p;x}‘ /etc/passwd # 在匹配行前插入空行
  9. sed ‘{x;p;x}‘ /etc/passwd # 在每一行前面插入空行
  10. sed ‘/pattern/i\new line‘ file # 在匹配行前插入一行new line
  11. 顯示行號,‘=’ 命令能顯示行號,但是行號是單獨的一行,若想行號後面跟該行的內容,需要再進行處理
  12. sed ‘=‘ file | sed ‘N;s/\n/\t/‘
  13. 調換兩個字符串位置:
  14. head -n2 1.txt|sed -r ‘s/(root)(.*)(bash)/\3\2\1/‘
    #在sed中可以用()去表示一個整體,123分別表示一個括號內容
  15. 打印文件中特定的某行到某行之間的內容
    sed -n ‘/起始內容/,/終止內容/p‘ filename
  16. 把一個文件多行連接成一行
    cat filename|xargs|sed ‘s/ /+/g‘
  17. 在文件中某一行最後添加一個數字
    sed ‘s/(^a.)/\1 12/‘ test
    或者sed ‘s/.
    /& 12/‘ test
  18. 使用sed打印1到100行包含某個字符串的行
    sed -n ‘1,100{/abc/p}‘ 1.txt
  19. 轉換大小寫字母
    #sed中使用\u表示大寫,\l表示小寫
    sed ‘s/\b[a-z]/\u&/g‘ filename #每個單詞的第一個小寫字母變大寫
    sed ‘s/[a-z]/\u&/g‘ filename #大寫替換小寫
    sed ‘s/[A-Z]/\l&/g‘ filename #大寫變成小寫
  20. vim+sed刪除行首數字和空字符
    在vim下輸入:%s/^[0-9][0-9]// 刪除行首數字
    sed -i ‘s/^
    //g‘ filename #刪除行首所有空字符
    練手腳本.note
  21. grep -v ^# filename|sed /^[[:space:]]*$/d|sed /^$/d #刪除文本中的空行、以空格組成的行及#註釋的行
  22. sed -i ‘20,30s/^/#/‘ filename #給20到30行開頭加上#號

sed用法