[英]Sed: delete lines without pattern except first
如何刪除除第一行之外與模式不匹配的行?
要刪除除第一行之外的行,我使用sed '1!d'
要刪除與模式不匹配的行,我使用sed '/pattern/!d'
我怎樣才能同時使用這兩個條件? 像sed '1!/pattern/!d'
這樣的東西不起作用,說未知命令:'/'
例如(如果模式=“rcu”)來自輸入
PID PPID PRI NI VSZ RSS STAT TIME CMD
1 0 19 0 33664 4832 Ss 00:00:07 /sbin/init splash
2 0 19 0 0 0 S 00:00:00 [kthreadd]
3 2 39 -20 0 0 I< 00:00:00 [rcu_gp]
4 2 39 -20 0 0 I< 00:00:00 [rcu_par_gp]
8 2 39 -20 0 0 I< 00:00:00 [mm_percpu_wq]
9 2 19 0 0 0 S 00:00:04 [ksoftirqd/0]
得到
PID PPID PRI NI VSZ RSS STAT TIME CMD
3 2 39 -20 0 0 I< 00:00:00 [rcu_gp]
4 2 39 -20 0 0 I< 00:00:00 [rcu_par_gp]
謝謝
輸出第一行和所有包含rcu
:
sed -n '1p; /rcu/p' file
您還可以制作一個腳本來讀取文件並“提取”與模式不匹配的第一行(到另一個臨時文件或字符串),進行其他操作,例如刪除要刪除的行並粘貼該行回到文件中的相同位置。
正如你所標記的awk
awk '{if ($0~/rcu/) print}'
演示:
$ cat file1.txt
PID PPID PRI NI VSZ RSS STAT TIME CMD
1 0 19 0 33664 4832 Ss 00:00:07 /sbin/init splash
2 0 19 0 0 0 S 00:00:00 [kthreadd]
3 2 39 -20 0 0 I< 00:00:00 [rcu_gp]
4 2 39 -20 0 0 I< 00:00:00 [rcu_par_gp]
8 2 39 -20 0 0 I< 00:00:00 [mm_percpu_wq]
9 2 19 0 0 0 S 00:00:04 [ksoftirqd/0]
$ awk '{if ($0~/rcu/) print}' file1.txt
3 2 39 -20 0 0 I< 00:00:00 [rcu_gp]
4 2 39 -20 0 0 I< 00:00:00 [rcu_par_gp]
$
如果當你說except the first
如果你的意思是except the first line of the input even if it doesn't match the regexp
那么這就是你想要的:
$ awk '/rcu/ || NR==1' file
PID PPID PRI NI VSZ RSS STAT TIME CMD
3 2 39 -20 0 0 I< 00:00:00 [rcu_gp]
4 2 39 -20 0 0 I< 00:00:00 [rcu_par_gp]
或者,如果您的意思是except the first line that doesn't match the regexp
那么這就是您想要的:
$ awk '/rcu/ || !c++' file
PID PPID PRI NI VSZ RSS STAT TIME CMD
3 2 39 -20 0 0 I< 00:00:00 [rcu_gp]
4 2 39 -20 0 0 I< 00:00:00 [rcu_par_gp]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.