如何打印出以关键字开头并以带sed或awk的反斜杠连接的行



例如,我想打印出以set_2开始并与连接的行,如下所示。我想知道是否可以用sed、awk或任何其他文本处理命令行来实现它。

< Before >

set_1 abc def  
set_2 a b c d  
e f g h  
i j k l  
m n o p  
set_3 ghi jek  
set_2 aaa bbb  
ccc ddd  
eee fff  
set_4 1 2 3 4  

< After text process >

set_2 a b c d  
e f g h  
i j k l  
m n o p  
set_2 aaa bbb  
ccc ddd  
eee fff  

尝试以下操作:

awk -v st="set_2" '/^set/ {set=$1} /\$/ && set==st { prnt=1 } prnt==1 { print } !/\$/ { prnt=0 }' file

说明:

awk -v st="set_2" '                                # Pass the set to track as a variable st
/^set/ {
set=$1                                     # When the line begins with "set", track the set in the variable set
} 
/\$/ && set==st {                 
prnt=1                                     # When we are in the required set block and the line ends with "/", set a print marker (prnt) to 1                                
} 
prnt==1 { 
print                                       # When the print marker is 1, print the line                                    
} 
!/\$/ { 
prnt=0                                       # If the line doesn't end with "/". set the print marker to 0
}' file

你会尝试sed解决方案吗:

sed -nE '
/^set_2/ {                      ;# if the line starts with "set_2" execute the block
:a                              ;# define a label "a"
/\[[:space:]]*$/! {p; bb}      ;# if the line does not end with "", print the pattern space and exit the block
N                               ;# append the next line to the pattern space
ba                              ;# go to label "a"
}                               ;# end of the block
:b                              ;# define a label "b"
' file

请注意,插入字符类[[:space:]]*只是因为OP发布的示例在斜杠后面包含空格。

[备选方案]

如果perl是您的选择,以下也将起作用:

perl -ne 'print if /^set_2/..!/\s*$/' file

这个简单的awk命令应该完成以下工作:

awk '!/^[[:blank:]]/ {p = ($1 == "set_2")} p' file
set_2 a b c d
e f g h
i j k l
m n o p
set_2 aaa bbb
ccc ddd
eee fff

使用此awk:

awk -F'[[:blank:]]*' '$1 == "set_2" ||  $NF ~ /$/ {print $0;f=1} f && $1 == ""' file
set_2 a b c d
e f g h
i j k l
m n o p
set_2 aaa bbb
ccc ddd
eee fff

这可能对你有用(GNU sed(:

sed ':a;/set_2/{:b;n;/set_/ba;bb};d' file

如果一行包含set_2,则打印该行并继续打印,直到另一行含有set_,然后重复第一次测试。

否则删除该行。

最新更新