【发布时间】:2017-03-07 18:18:10
【问题描述】:
我正在尝试使用突出显示的搜索字符串打印整个文件的内容。
对于 Record 等于单行的简单文件,我可以使用以下方法轻松完成此操作:
grep --color=auto "myseacrchpattern" inputfile
这里我的记录是段落而不是单行。示例:
CREATE TABLE mytable ( id SERIAL,
name varchar(20),
cost int );
CREATE TABLE notmytable ( id SERIAL,
name varchar(20),
cost int );
如果我确实使用 grep 作为关键字:“notmytable”,它会给我彩色输出,但只打印该行。
grep --color=auto 'notmytable' inputfile
CREATE TABLE notmytable ( id SERIAL, # <-- "notmytable" is in red but its not the whole query
我需要这样的东西:
CREATE TABLE notmytable ( id SERIAL, # <---"notmytable" is in red
name varchar(20),
cost int );
我可以用 awk 或 perl 打印所需的段落,但如何着色:
awk -v RS=';' -v ORS=';\n' '/notmytable/' inputfile
CREATE TABLE notmytable ( id SERIAL,
name varchar(20),
cost int );
或 perl :
perl -00lne 'print $_ if /notmytable/' inputfile
CREATE TABLE notmytable ( id SERIAL,
name varchar(20),
cost int );
【问题讨论】:
-
对于 Perl,请参阅 Term::ANSIColor
-
perl -e 'use Term::ANSIColor; print color("red"), "Stop!\n", color("reset"); print color("green"), "Go!\n", color("reset");' -
在这种特殊情况下,您可以使用 grep 的上下文控制选项:
grep -A 2 notmytable input -
@Leon,我想到了但无法使用,因为行数在实际数据集中是动态的。
-
@PS。您可以使用此模块动态构建打印语句。