Sed命令常用用法

基本語法:
sed [options] commands inputfile

options:
-n:取消默認輸出
eg. sed -n '3 p' test.txt
-e:多條子命令時使用
eg. sed -e 's/a/A/' -e 's/b/B/' test.txt
eg. sed -e 's/a/A/;s/b/B/' test.txt
-f:將多條命令寫在腳本中,從腳本中讀取命令,此時commands參數是腳本名稱
cat a.sed
s/a/A/
s/b/B/
eg. sed -f a.sed test.txt
-i:直接在原文件上做修改
-r:允許使用擴展正則表達式

commands:[定位參數] [編輯命令]

  • 定位參數
    • 行號定位:
      • 單行號定位:x(表示具體一行)、$(特指最後一行)
        eg. sed -n ‘3 p’ test.txt
      • 連續行號定位:x,y(表示從第x行到第y行)、x,+n(表示從第x行開始以及之後的n行)
        eg. sed -n '3,4 p' test.txt
        eg. sed -n '3,+1 p' test.txt
      • 等差行號定位:x~step(表示從第n行開始,步長是step的那些行)
        eg. sed -n '3~2 p' test.txt
    • 正則表達式定位:/regexp/
      eg. sed -n '/abc.*abc/ p' test.txt
  • 編輯命令
    • 打印:p
      eg. sed -n '3 p' test.txt
    • 替換: s/pattern/replacement/[flag]
      flag:g(所有匹配到的都做替換)、n(n是一個具體的十進制數字,表示第n個匹配到的才做替換)
      eg. sed -i 's/abc.*abc/abc/g' test.txt
    • 刪除: d
      eg. sed -i '2 d' test.txt
    • 追加(在指定的行後增加一行): a string
      eg. sed -i '2 a abcde' test.txt
    • 插入(在指定的行前增加一行): i string
      eg sed -i '2 i abcde' test.txt
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章