使用awk或sed只有在模式中间的文本匹配时才能在模式(相同模式)之间进行打印 例如,假设文件包含
awk '$0 ~ /^#/{
start_flag=1;
}
$0 ~ /g$/{
mid_flag=1;
}
start_flag {
n=NR;
lines[NR];
}
$0 ~ /^#/
{
if (start_flag && mid_flag)
{
for (i=n; i<NR; i++)
print lines[i];
}
start_flag=0;
mid_flag=0;
delete lines
}' <file_name>
我希望打印两个'#'之间的块,其中field3 = g 我编写的脚本下面没有工作
field1=e
field2=f
field3=g
field4=h
预期的o / p是
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<div class="container">
<form class="form-horizontal">
<div class="row">
<div class="col-md-12">
<h2><p class="text-center">Personal Information</p></h2>
</div>
</div>
<div class="form-group">
<div class="col-md-2">
<select class="form-control">
<option value="mr">Mr.</option>
<option value="ms">Ms.</option>
</select>
</div>
<div class="col-md-4">
<input type="text" class="form-control" id="firstname" class="form-control" placeholder="First name *">
</div>
<div class="col-md-4">
<input type="text" class="form-control" id="lastname" class="form-control" placeholder="Last name *">
</div>
<div class="col-md-2">
<div class='input-group date' id='datetimepicker2'>
<input type='text' class="form-control" />
<span class="input-group-addon">
<span class="glyphicon glyphicon-calendar"></span>
</span>
</div>
</div>
</div>
<div class="form-group">
<div class="col-md-4">
<input type="text" id="mobile" class="form-control" placeholder="Mobile *">
</div>
<div class="col-md-4">
<input type="email" id="email" class="form-control" placeholder="Email *">
</div>
<div class="col-md-4">
<input type="email" id="emailconf" class="form-control" placeholder="Confirm Email *">
</div>
</div>
<div class="form-group">
<div class="col-md-12">
<input type="text" id="address1" class="form-control" placeholder="Address *">
</div>
</div>
<div class="form-group">
<div class="col-md-4">
<input type="text" id="suburb" class="form-control" placeholder="Suburb *">
</div>
<div class="col-md-4">
<select class="form-control">
<option class="collapse" value="mr">Info</option>
</select>
</div>
<div class="col-md-4">
<input type="text" id="postcode" class="form-control" placeholder="Post Code *">
</div>
</div>
</form>
</div>
答案 0 :(得分:2)
$ awk -v RS='#[^\n]*\n' -v ORS='' '/field3=g/' ip.txt
field1=e
field2=f
field3=g
field4=h
-v RS='#[^\n]*\n'
将输入记录分隔符设置为#
,包括下一个换行符-v ORS=''
将输出记录分隔符设置为空字符串/field3=g/
打印包含文字field3=g
@ NeronLeVelu建议替代方法,以确保在行首
匹配#
awk -v RS='(^|\n)[[:blank:]]*#[^\n]*\n' '/field3=g/' ip.txt
答案 1 :(得分:0)
使用grep
grep -A1 -B2 "field3=g" file
-A
和-B
选项在匹配行之前和之后打印NUM行尾随上下文。
你明白了,
field1=e
field2=f
field3=g
field4=h
仅限乐趣
如果您要使用field3=g
打印所有相邻记录以匹配sed
sed -n '/^#/{
:c; :a; n; H;
/^#/{bc};
/field3=g/{x; s/.*#[^\n]*\n//;p;:d;n;/^#/{bc}; p; bd}; ba;
};:b' file
你明白了,
field1=e
field2=f
field3=g
field4=h
或使用awk
awk '
/^#/{i=0; f=0}
{m[++i]=$0}
/field3=g/{for(j=2; j<=i; ++j) print m[j]; f=1; next}
f' file
你得到相同的结果