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)

猜你喜欢

转载自ilnba.iteye.com/blog/1564206
sed