Sed & Awk每日一例之二
通过p命令,可以输出当前的模式空间(pattern space)。
1、文件中的每行输出两次
$ sed 'p' employee.txt
101,John Doe,CEO
101,John Doe,CEO
102,Jason Smith,IT Manager
102,Jason Smith,IT Manager
103,Raj Reddy,Sysadmin
103,Raj Reddy,Sysadmin
104,Anand Ram,Developer
104,Anand Ram,Developer
105,Jane Miller,Sales Manager
105,Jane Miller,Sales Manager
2、文件中的每行只输出一次,用 -n 参数
$ sed -n 'p' employee.txt
101,John Doe,CEO
102,Jason Smith,IT Manager
103,Raj Reddy,Sysadmin
104,Anand Ram,Developer
105,Jane Miller,Sales Manager
3、只输出第二行
$ sed -n '2 p' employee.txt
102,Jason Smith,IT Manager
4、输出第1到第4行
$ sed -n '1,4 p' employee.txt
101,John Doe,CEO
102,Jason Smith,IT Manager
103,Raj Reddy,Sysadmin
104,Anand Ram,Developer
5、输出第2到最后一行
$ sed -n '2,$ p' employee.txt
102,Jason Smith,IT Manager
103,Raj Reddy,Sysadmin
104,Anand Ram,Developer
105,Jane Miller,Sales Manager
6、输出奇数行
$ sed -n '1~2 p' employee.txt
101,John Doe,CEO
103,Raj Reddy,Sysadmin
105,Jane Miller,Sales Manager
n~m 表示从第n行开始,每m行执行一次,1~2 匹配 1,3,5,7.... ;2~2 匹配 2,4,6,8 .... ; 2~3 匹配 2,5,8,11 ....
7、输出匹配 Jane 的行
$ sed -n '/Jane/ p' employee.txt
105,Jane Miller,Sales Manager
8、从匹配 Jason的行开始输出到第4行
$ sed -n '/Jason/,4 p' employee.txt
102,Jason Smith,IT Manager
103,Raj Reddy,Sysadmin
104,Anand Ram,Developer
9、从第一个匹配 Raj 的行输出到最后
$ sed -n '/Raj/,$ p' employee.txt
103,Raj Reddy,Sysadmin
104,Anand Ram,Developer
105,Jane Miller,Sales Manager
10、输出从 Raj 到 Jane 之间的行
$ sed -n '/Raj/,/Jane/ p' employee.txt
103,Raj Reddy,Sysadmin
104,Anand Ram,Developer
105,Jane Miller,Sales Manager
11、输出匹配 Jason 的行和其后面的2行
$ sed -n '/Jason/,+2 p' employee.txt
102,Jason Smith,IT Manager
103,Raj Reddy,Sysadmin
104,Anand Ram,Developer