打印文件中从包含 的行^# fish,
到(但不包括)包含 的下一行的所有行的好方法是什么^#
?
答案1
使用 AWK:
awk '/^#/ { inblock = 0 }; /^# fish/ { inblock = 1 }; inblock'
这实际上会打印所有以 开头的块# fish
。要在第一个块之后停止:
awk 'inblock && /^#/ { exit }; /^# fish/ { inblock = 1 }; inblock'
inblock
两种变体的工作原理都是在处理感兴趣的块中的行时将变量设置为 1;当为 1时,最后一条inblock
语句应用默认操作(打印当前行) 。inblock
答案2
珀尔
正则表达式重复查找从 开始并在与换行符相邻的line boundary
# fish
最短(非贪婪)处或文件本身的最末尾处结束的块。#
然后打印出匹配的部分。
perl -l -0777ne 'print $& while /^#\sfish.+?(?=\n(?:#|\z))/msg' yourfile
sed -e '
/^# fish/!d; # havent yet seen the fish, so skip
$b; N; # seen the fish so grab the next line unless its the last in which case promptly show and quit
/\n#/!s/^/\n/; # not seen a line with "#" so go read next
/^\n/D; #
h; # whole block /# fish/.../#/ with us now
s/\(.*\)\n.*/\1/; # remove the last line, i.e., trailing # line
p; # show the block now
g; # retrieve orig unmodified block
s/.*\n/\n/; D; # keep the last line and go back for more...
' yourfile