【发布时间】:2016-01-13 04:33:46
【问题描述】:
我的文件:
...
str
...
str
...
我用:
sed '/str/q' myfile
打印出来:
...
str
但我需要:
...
str
...
str
我怎样才能得到上面的结果? (... 是其他字符串。)
【问题讨论】:
-
如果
str在文件中没有出现两次,你想输出什么?
我的文件:
...
str
...
str
...
我用:
sed '/str/q' myfile
打印出来:
...
str
但我需要:
...
str
...
str
我怎样才能得到上面的结果? (... 是其他字符串。)
【问题讨论】:
str在文件中没有出现两次,你想输出什么?
根据您在问题中未说明的要求,这可能是您想要的:
$ awk '1; /str/&&c++{exit}' file
...
str
...
str
【讨论】:
使用 sed
sed '/str/{x;//q;x;h}' file
...
str
...
str
【讨论】:
str 存在,这将重复第一个str 作为最后一行。也许sed '/str/{x;//{x;q};x;h}' file 更安全?
awk '/str/{++i}7;i==2{exit}' file
应该可以满足您的要求。
它记录变量i中的匹配计数,当计数==2退出处理时。
【讨论】:
sed '/str/{:second n; /str/q; b second}' myfile
当 SED 找到第一个“str”时,开始一个循环,直到找到下一个。
更多详情:SED loop match
【讨论】:
一种方式:
awk '/str/ && f{print;exit}/str/{f=1}1' f=0 file
当第一次遇到 /str/ 时,将变量设置为 1 并继续打印。下次遇到时,打印该行并停止执行。
【讨论】:
另一种方式,计算匹配数并在第二个匹配时退出。打印其他行。
awk 'BEGIN {m=0}; {print}; /str/ {m++; if ( m == 2 ) { exit; } }' file
【讨论】:
如果 Perl 是一个选项:
perl -pe '$m++ if /str/; exit if $m==2' file
计算匹配项。如果匹配 == 2,则退出。
【讨论】: