5.把模式空間寫入到檔案(w命令)

來源:互聯網
上載者:User

利用sed的w命令,你可以把當前模式空間的內容寫入到一個檔案裡。預設情況下,模式空間的內容輸出到stdout,因此如果你想輸出到一個檔案裡,而非螢幕,你應該加上-n選項。


下面是一些例子:

把exployee.txt的內容寫入到檔案output.txt裡同時顯示在螢幕上):

$ sed 'w output.txt'employee.txt

101,John Doe,CEO

102,Jason Smith,ITManager

103,RajReddy,Sysadmin

104,AnandRam,Developer

105,JaneMiller,Sales Manager

$ cat output.txt

101,John Doe,CEO

102,Jason Smith,ITManager

103,RajReddy,Sysadmin

104,AnandRam,Developer

105,JaneMiller,Sales Manager


把exployee.txt的內容寫入到output.txt裡,但不顯示在螢幕上:

$ sed -n 'woutput.txt' employee.txt

$ cat output.txt

101,John Doe,CEO

102,Jason Smith,ITManager

103,RajReddy,Sysadmin

104,AnandRam,Developer

105,JaneMiller,Sales Manager


只把第二行寫入:

$ sed -n '2 woutput.txt' employee.txt

$ cat output.txt

102,Jason Smith,ITManager


把第一行到第四行寫入:

$ sed -n '1,4 woutput.txt' employee.txt

$ cat output.txt

101,JohnDoe,CEO

102,Jason Smith,ITManager

103,RajReddy,Sysadmin

104,AnandRam,Developer


把從第二行到最後一行寫入:

$ sed -n '2,$ woutput.txt' employee.txt

$ cat output.txt

102,Jason Smith,ITManager

103,RajReddy,Sysadmin

104,AnandRam,Developer

105,JaneMiller,Sales Manager


僅僅把奇數行寫入:

$ sed -n '1~2 woutput.txt' employee.txt

$ cat output.txt

101,John Doe,CEO

103,RajReddy,Sysadmin

105,JaneMiller,Sales Manager


把匹配'Jane'的行寫入:

$ sed -n '/Jane/ woutput.txt' employee.txt

$ cat output.txt

105,JaneMiller,Sales Manager


把第一次匹配'Jasion'的行到最後一行之間所有的行寫入:

$ sed -n '/Jason/,4w output.txt' employee.txt

$ cat output.txt

102,Jason Smith,ITManager

103,RajReddy,Sysadmin

104,AnandRam,Developer


如果在前四行沒有匹配'Jason'的行,這個命令僅僅把第四行以後匹配'Jason'的行寫入到檔案。


把第四次匹配'Raj'的行到最後一行之間的行寫入:

$ sed -n '/Raj/,$ woutput.txt' employee.txt

$ cat output.txt

103,RajReddy,Sysadmin

104,AnandRam,Developer

105,JaneMiller,Sales Manager



把第一次匹配'Raj'的行到匹配'Jane'的行之間的行寫入:

$ sed -n'/Raj/,/Jane/ w output.txt' employee.txt

$ cat output.txt

103,RajReddy,Sysadmin

104,AnandRam,Developer

105,JaneMiller,Sales Manager


把匹配'Jason'的行及下面的兩行寫入:

$ sed -n '/Jason/,+2w output.txt' employee.txt

$ cat output.txt

102,Jason Smith,ITManager

103,RajReddy,Sysadmin

104,AnandRam,Developer


注意:你可能不經常使用w命令。大多數人儲存一個檔案時,用UNIX輸出重新導向來代替sed的w操作。

比如:sed 'p'exployee.txt > output.txt




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

聯繫我們

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