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