sed 系列: 怎样用sed写文件

In this article, let us review how to extract part of one file and write it to another file using sed.

Sed provides “w” command to write the pattern space data to a new file.

Sed creates or truncates the given filename before reads the first input line and it writes all the matches to a file without closing and re-opening the file.

Syntax:
#sed 'ADDERSSw outputfile' inputfilename
#sed '/PATTERN/w outputfile' inputfilename

Sed reads a line and place it in a pattern buffer and writes the pattern buffer to the given output file according to the supplied commands.
建立测试文件
# cat thegeekstuff.txt
1. Linux - Sysadmin, Scripting etc.
2. Databases - Oracle, mySQL etc.
3. Hardware
4. Security (Firewall, Network, Online Security etc)
5. Storage
6. Cool gadgets and websites
7. Productivity (Too many technologies to explore, not much time available)
8. Website Design
9. Software Development
10.Windows- Sysadmin, reboot etc.
例子1: 把第一行写入一个文件
$ sed -n '1w output.txt' thegeekstuff.txt

$ cat output.txt
1. Linux - Sysadmin, Scripting etc.

例子2:把第一行和最后一行写入一个文件
$ sed -n -e '1w output.txt' -e '$w output.txt' thegeekstuff.txt

$ cat output.txt
1. Linux - Sysadmin, Scripting etc.
10.Windows- Sysadmin, reboot etc.

例子3:匹配行写入
$ sed -n -e '/Storage/w output.txt' -e '/Sysadmin/w output.txt' thegeekstuff.txt

$ cat output.txt
1. Linux - Sysadmin, Scripting etc.
5. Storage
10.Windows- Sysadmin, reboot etc.

例子4:从匹配行一直到末尾写入文件
$ sed -n '/Storage/,$w output.txt' thegeekstuff.txt

$ cat output.txt
5. Storage
6. Cool gadgets and websites
7. Productivity (Too many technologies to explore, not much time available)
8. Website Design
9. Software Development
10.Windows- Sysadmin, reboot etc.

例子5:从匹配行和皮排行后的两行写入文件
$ sed -n '/Storage/,+2w output.txt' thegeekstuff.txt

$ cat output.txt
5. Storage
6. Cool gadgets and websites
7. Productivity (Too many technologies to explore, not much time available)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值