5. 将模式空间写入文件(w 命令)
使用 sed 的 w
命令,可以将当前模式空间写入文件。
默认情况下,根据 sed 标准流程,模式空间将打印到 stdout
,因此如果您希望输出到文件而不是屏幕,您还应该使用 sed 选项 -n
。
示例
以下是一些示例。
Example1:将 employee.txt
文件的内容写入到 output.txt
文件(并在屏幕上显示)
$ sed 'w output.txt' employee.txt 101,John Doe,CEO 102,Jason Smith,IT Manager 103,Raj Reddy,Sysadmin 104,Anand Ram,Developer 105,Jane Miller,Sales Manager $ cat output.txt 101,John Doe,CEO 102,Jason Smith,IT Manager 103,Raj Reddy,Sysadmin 104,Anand Ram,Developer 105,Jane Miller,Sales Manager
Example2:将 employee.txt
文件的内容写入到 output.txt
文件(但不写入屏幕)
$ sed -n 'w output.txt' employee.txt $ cat output.txt 101,John Doe,CEO 102,Jason Smith,IT Manager 103,Raj Reddy,Sysadmin 104,Anand Ram,Developer 105,Jane Miller,Sales Manager
Example3:仅写入第 2 行
$ sed -n '2 w output.txt' employee.txt $ cat output.txt 102,Jason Smith,IT Manager
Example4:写入第 1-4 行
$ sed -n '1,4 w output.txt' employee.txt $ cat output.txt 101,John Doe,CEO 102,Jason Smith,IT Manager 103,Raj Reddy,Sysadmin 104,Anand Ram,Developer
Example5:写入从第 2 行开始一直到最后一行
$ sed -n '2,$ w output.txt' employee.txt $ cat output.txt 102,Jason Smith,IT Manager 103,Raj Reddy,Sysadmin 104,Anand Ram,Developer 105,Jane Miller,Sales Manager
Example6:仅写入奇数行
$ sed -n '1~2 w output.txt' employee.txt $ cat output.txt 101,John Doe,CEO 103,Raj Reddy,Sysadmin 105,Jane Miller,Sales Manager
Example7:写入匹配到 "Jane"
的行
$ sed -n '/Jane/ w output.txt' employee.txt $ cat output.txt 105,Jane Miller,Sales Manager
Example8:写入从第一次匹配到 "Jason"
开始一直到第 4 行:
$ sed -n '/Jason/,4 w output.txt' employee.txt $ cat output.txt 102,Jason Smith,IT Manager 103,Raj Reddy,Sysadmin 104,Anand Ram,Developer
"Jason"
,则此命令仅写入第 4 行之后与 "Jason"
匹配的行。
Example9:写入从第一次匹配到 "Raj"
的行开始直到最后一行之间的所有行
$ sed -n '/Raj/,$ w output.txt' employee.txt $ cat output.txt 103,Raj Reddy,Sysadmin 104,Anand Ram,Developer 105,Jane Miller,Sales Manager
Example10:写入从匹配到 "Raj"
的行开始直到匹配到 "Jane"
的行结束之间的所有行
$ sed -n '/Raj/,/Jane/ w output.txt' employee.txt $ cat output.txt 103,Raj Reddy,Sysadmin 104,Anand Ram,Developer 105,Jane Miller,Sales Manager
Example11:写入与 "Jason"
匹配的行以及紧随其后的 2 行
$ sed -n '/Jason/,+2 w output.txt' employee.txt $ cat output.txt 102,Jason Smith,IT Manager 103,Raj Reddy,Sysadmin 104,Anand Ram,Developer
您可能不经常使用w
命令。 大多数人习惯使用 UNIX
输出重定向
来将 sed 的输出存储到文件中。
例如:
sed 'p' employee.txt > output.txt