4.刪除命令d

來源:互聯網
上載者:User

使用 sed 的d 指令,你可以刪除一些行。請注意這些行只是在輸出的時候被刪除。和其他命令一樣,d命令不會修改源檔案的內容。


預設情況下,在使用sed前,如果你指定任何位址範圍 ,它將匹配所有的行。因此,下列的例子將不列印任事,因為它匹配了 employee.txt中所有的行並刪除他們。


sed 'd' employee.txt


在刪除時,指定一個位址範圍會很有用。下面是一些例子:

只刪除第二行:

$ sed '2 d'employee.txt

101,John Doe,CEO

103,RajReddy,Sysadmin

104,AnandRam,Developer

105,JaneMiller,Sales Manager


刪除1~4行:

$ sed '1,4 d'employee.txt

105,JaneMiller,Sales Manager


刪除從第二行到最後一行:

$ sed '2,$ d'employee.txt

101,John Doe,CEO


只刪除技術行:

$ sed '1~2 d'employee.txt

102,Jason Smith,ITManager

104,AnandRam,Developer


刪除所有包含'Manager'的行:

$ sed '/Manager/ d'employee.txt

101,John Doe,CEO

103,RajReddy,Sysadmin

104,AnandRam,Developer


刪除第一次包含'Jason'的行到第四行:

$ sed '/Jason/,4 d'employee.txt

101,John Doe,CEO

105,JaneMiller,Sales Manager

如果在前四行沒有匹配'Jason'的行,這個命令只刪除第四行以後匹配'Jason'的行。


刪除從第一次匹配'Raj'的行到最後一行:

$ sed '/Raj/,$ d'employee.txt

101,John Doe,CEO

102,Jason Smith,ITManager


刪除從第一次匹配'Raj'的行到匹配'Jane'之間的行:

$ sed '/Raj/,/Jane/d' employee.txt

101,John Doe,CEO

102,Jason Smith,ITManager


刪除匹配'Jason'的行及它下面兩行:

$ sed '/Jason/,+2 d'employee.txt

101,John Doe,CEO

105,JaneMiller,Sales Manager


一些有用的刪除例子
下面的例子在日常的應用中很有用。

從一個檔案刪除所有空行:

sed '/^$/ d'employee.txt


刪除所有注釋行假設注釋以#開頭):

sed '/^#/ d'employee.txt


注意:當你使用多個sed命令的時候,d命令會刪除所有匹配的行,其他的命令將不會作用在這些刪除的行上。


本文出自 “老段工作室” 部落格,請務必保留此出處http://lduan.blog.51cto.com/5428084/1303032

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.