Linux系統:sed 字元替換命令,linuxsed

來源:互聯網
上載者:User

Linux系統:sed 字元替換命令,linuxsed
sed 命令

sed 是一種幾乎包括在所有 UNIX 平台(包括 Linux)的輕量級流編輯器。sed 主要是用來將資料進行選取、替換、刪除、新增的命令。

格式:

sed [選項] ‘[動作]’ 檔案名稱

選項:-n:一般 sed 命令會把所有資料都輸出到螢幕,如果加入此選項則只會把經過 sed 命令處理的行輸出到螢幕。 -e:允許對輸入的資料應用多條 sed 命令編輯。 -i:用 sed 的修改結果直接修改讀取資料的檔案,而不是由螢幕輸出。動作:a:追加,在當前行後添加一行或多行。 c:行替換,用 c 後面的字串替換原資料行。 i:插入,在當前行前插入一行或多行。 d:刪除,刪除指定的行。 p:列印,輸出指定的行。 s:字元替換,用一個字串替換另外一個字串。格式為“行範圍s/舊字串/新字串/g”(和 vim 中的替換格式類似)行資料操作
[root@localhost ~]# sed '2p' student.txt #沒有 -n 選項輸出所有內容,而且會重複,'2p' 代表列印第二行ID  Name    Gender  Mark1   stu1    F       951   stu1    F       952   stu2    F       853   stu3    F       75[root@localhost ~]# sed -n '2p' student.txt #有-n 選項則列印指定行1   stu1    F   95
[root@localhost ~]# sed '2d' student.txt #'2d' 代表刪除第二行內容,不修改原檔案ID  Name    Gender  Mark2   stu2    F       853   stu3    F       75[root@localhost ~]# sed '2,4d' student.txt #'2,4d' 代表刪除第二行到第四行所有內容,不修改原檔案ID  Name    Gender  Mark
[root@localhost ~]# sed '2a hello' student.txt #在第二行後追加一行內容為 hello,不修改原檔案ID  Name    Gender  Mark1   stu1    F       95hello2   stu2    F       853   stu3    F       75[root@localhost ~]# sed '2i hello' student.txt #在第二行前插入一行內容為 hello,不修改原檔案ID  Name    Gender  Markhello1   stu1    F       952   stu2    F       853   stu3    F       75
[root@localhost ~]# sed '4c test' student.txt #替換第四行內容為 test,不修改原檔案ID  Name    Gender  Mark1   stu1    F       952   stu2    F       85test
字串替換

sed ‘s/舊字串/新字串/g’ 檔案名稱 # g 代表替換所有字串

[root@localhost ~]# sed '4s/75/100/g' student.txt #替換第四行的 75 為 100,不修改原檔案ID  Name    Gender  Mark1   stu1    F       952   stu2    F       853   stu3    F       100[root@localhost ~]# sed -i '4s/75/100/' student.txt # -i 選項會修改原檔案內容,但不再列印到螢幕[root@localhost ~]# cat student.txt #原檔案內容已更改 ID  Name    Gender  Mark1   stu1    F       952   stu2    F       853   stu3    F       100
[root@localhost ~]# sed -e 's/stu1//g;s/stu3//g' student.txt #-e 執行多條語句,用分號隔開,將 stu1 和 stu3 內容替換為空白,替換原檔案用 -ie,-ei 會報錯ID  Name    Gender  Mark1           F       952   stu2    F       853           F       100

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.