从awk脚本中的variablesstring中删除最后一行

我做了以下脚本:

awk ' { if ($1 ~ /^d/) { a=a $0; } .... -> rest code if (p == 1) { b=a; print b; } } ' input.txt 
  • find一个结果,我将在后面工作,所以不能改变它的结构
  • b – 存储一部分,比如标题

input文件:

  d1file some text edont show that d2file like it d3file need to remove 

结尾的内容:

  d1file some text d2file like it d3file need to remove 

我想做什么:

如果$ 1d开始,我将它存储在一个variables中。 后来我喜欢把a移到b,并从b中删除最后一行,所以b的输出应该是:

  d1file some text d2file like it 

我正在寻找任何解决scheme,但没有运气。 我正在考虑将内容存储为数组,并使用index-1来循环删除最后一行,但是我无法工作。

有没有办法做到这一点?

 awk ' /^d/ { a = a $0 "\n"} # accumulate lines starting with d END { sub(/\n[^\n]*\n$/, "", a); # remove the last line print a } ' input.txt 

这应该做的工作:

 awk 'BEGIN {counter=1} { if ($1 ~ /^d/) array[counter++]=$0} END { for (element=1;element<counter-1;element++) print array[element]}' input.txt 

这将所有的搜索点击在一个数组中,然后在最后打印数组的最后一个元素

你可以使用这个简单的awk命令:

 awk '$1 ~ /^d/{if(p) a=ap; p=$0 ORS} END{printf a}' input.txt d1file some text d2file like it 

我不明白在这里的最终目标,这似乎是一个奇怪的方式做事情,但这应该做你想做的事情:

 awk 'tmp{b=b (b?ORS:"") tmp; tmp=""}; /^d/{tmp=$0;next} END{a=b (tmp?ORS:"") tmp; ...do something with a and b here...} input.txt 

例:

 $ cat input.txt d1file some text edont show that d2file like it d3file need to remove $ awk 'tmp{b=b (b?ORS:"") tmp; tmp=""}; /^d/{tmp=$0;next} END{a=b (tmp?ORS:"") tmp; print "--"; print a; print "--"; print b; print "--"}' input.txt -- d1file some text d2file like it d3file need to remove -- d1file some text d2file like it -- 
 awk '/^d/{a[nr++]=$0}END{for(i=0;i<nr-1;i++) print a[i]}'input.txt 

/^d/选择以d开头的行,并执行该操作,如果以d开头,则保存数组a的行

for中的for将打印排除最后一个数组