我遇到一个问题,我使用 awk 查找一行并在上面打印两行
文件 test.txt 文件内如下”
{ TABLE "sacro".issue row size = 149 number of columns = 9 index size = 0 }
{ unload file name = issue00106.unl number of rows = 74 }
create table "sacro".issue
(
issue_no serial not null constraint "sacro".nnc_issue00,
user_logged varchar(8,1) not null constraint "sacro".nnc_issue01,
issue_status_code integer not null constraint "sacro".nnc_issue02,
issue_cat_code varchar(2) not null constraint "sacro".nnc_issue03,
issue_descr text not null constraint "sacro".nnc_issue04,
issue_feedback text,
user_action varchar(8,1),
date_logged date not null constraint "sacro".nnc_issue05,
date_compl date
);
revoke all on "sacro".issue from "public" as "sacro";
{ TABLE "sacro".issue_category row size = 104 number of columns = 2 index size = 8 }
{ unload file name = issue00107.unl number of rows = 5 }
create table "sacro".issue_category
(
issue_cat_code varchar(2) not null constraint "sacro".nnc_iss_cat00,
issue_cat_descr varchar(100),
primary key (issue_cat_code) constraint "sacro".pkc_issuecategory
);
revoke all on "sacro".issue_category from "public" as "sacro";
{ TABLE "sacro".issue row size = 149 number of columns = 9 index size = 0 }
{ unload file name = issue00106.unl number of rows = 74 }
我正在搜索的行如下:
create table "sacro".issue
我正在运行的命令是:
cat test.txt | awk '{a[NR]=$0} $0~s {f=NR} END {for (i=f-B;i<=f+A;i++) print a[i]}' B=2 A=0 s='create table \"sacro\".issue'
当我运行该命令时,它找到行 create table "sacro".issue_category。有没有办法 grep 查找我需要的行,就像我使用 grep -w 一样。不幸的是,下面的 grep 命令在 HPUX 上不起作用:
cat test.txt | grep -B 2 -w "create table \"sacro\".issue" | head -1
我想要的结果应该是(使用头-1):
{ unload file name = issue00106.unl number of rows = 74 }
答案1
sed -e '
1N # get 2nd line in pattern space
$!N # get 3rd line in pattern space
/\ncreate table "sacro"\.issue$/P # if the last portion of matches, show 1st portion
D # strip 1st portion & reapply sed code on what
# remains of the pattern space
' test.txt
grep -B 2 'create table "sacro"\.issue$' test.txt | sed q
答案2
首先,没有理由grep
不能这样做。哦,请注意,您不需要cat
, 和 都grep
可以awk
接受输入文件名:
$ grep -xB2 'create table "sacro".issue' file
{ unload file name = issue00106.unl number of rows = 74 }
create table "sacro".issue
因此,如果您只想要第一行,请执行以下操作:
$ grep -xB2 'create table "sacro".issue' file | head -n1
{ unload file name = issue00106.unl number of rows = 74 }
这-x
意味着“匹配整行”,确保create table "sacro".issue_category
不打印该行。意思-B2
是“同时打印前两行。
awk
您也可以按照要求进行:
$ awk -vs='create table "sacro".issue' '($0==s){print b2}{b2=b1; b1=$0}' file
{ unload file name = issue00106.unl number of rows = 74 }