Separate by blank lines in bash

蓝咒 提交于 2019-12-23 02:44:15

问题


I have an input like this:

Block 1:
line1
line2
line3
line4

Block 2:
line1
line2

Block 3:
line1
line2
line3

This is an example, is there an elegant way to print Block 2 and its lines only without rely on their names? It would be like "separate the blocks by the blank line and print the second block".


回答1:


try this:

 awk '!$0{i++;next;}i==1' yourFile

considering performance, also can add exit after 2nd block was processed:

 awk '!$0{i++;next;}i==1;i>1{exit;}' yourFile

test:

kent$  cat t
Block 1:
line1
line2
line3
line4

Block 2:
line1
line2

Block 3:
line1
line2
line3

kent$  awk '!$0{i++;next;}i==1' t           
Block 2:
line1
line2

kent$  awk '!$0{i++;next;}i==1;i>1{exit;}' t
Block 2:
line1
line2



回答2:


Set the record separater to the empty string to separate on blank lines. To print the second block:

$ awk -v RS=  'NR==2{ print }'

(Note that this only separates on lines that do not contain any whitespace. A line containing only white space is not considered a blank line.)



来源:https://stackoverflow.com/questions/7892256/separate-by-blank-lines-in-bash

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!