在下面的示例中^[-是用于着色终端输出的转义字符(只需键入ctrl+v++)。
1)我的档案:
-------- just to mark start of file ----------
^[[1;31mbla bla bla^[[0m
^[[0;36mTREE;01;^[[0m
^[[1;31m^[[0m
^[[1;31m^[[1;31mapple tree:^[[0m^[[0m
^[[1;31m4 apples^M^M^[[0m
^[[1;31m6 leafs^M^[[0m
^[[0;36mTREE;02;^[[0m
^[[0;36mTREE;03;^[[0m
withered
^[[0;36mTREE;04;^[[0m
^[[0;36mTREE;05;^[[0m
^[[0;36mTREE;06;^[[0m
^[[0;36mTREE;07;^[[0m
^[[1;31m^[[0m
^[[1;31m^[[1;31mcherry tree:^[[0m^[[0m
^[[1;31mbig branches^M^M^[[0m
^[[1;31mtchick roots^M^[[0m
^[[0;36mTREE;08;^[[0m
^[[0;36mMy tree ^[[0m I have tree house on it^[[0;31m:-)^[[0m
^[[0;36mTREE;09;^[[0m
-------- just to mark end of file ----------
2)我想去掉所有的“空标签”-所有的标签下都没有评论。
所以我想达到的结果是:
-------- just to mark start of results ----------
^[[1;31mbla bla bla^[[0m
^[[0;36mTREE;01;^[[0m
^[[1;31m^[[0m
^[[1;31m^[[1;31mapple tree:^[[0m^[[0m
^[[1;31m4 apples^M^M^[[0m
^[[1;31m6 leafs^M^[[0m
^[[0;36mTREE;03;^[[0m
withered
^[[0;36mTREE;07;^[[0m
^[[1;31m^[[0m
^[[1;31m^[[1;31mcherry tree:^[[0m^[[0m
^[[1;31mbig branches^M^M^[[0m
^[[1;31mtchick roots^M^[[0m
^[[0;36mTREE;08;^[[0m
^[[0;36mMy tree ^[[0m I have tree house on it^[[0;31m:-)^[[0m
-------- just to mark end of results ----------
3)我知道:
pcregrep -M 'TREE.*\n(\n|\s)+(?=.*TREE|\z)' my_file
它能像我所期望的那样工作-它只留下没有注释的标签
-------- just to mark start of results ----------
^[[0;36mTREE;02;^[[0m
^[[0;36mTREE;04;^[[0m
^[[0;36mTREE;05;^[[0m
^[[0;36mTREE;06;^[[0m
^[[0;36mTREE;09;^[[0m
-------- just to mark end of results ----------
4)但是命令:
pcregrep -Mv 'TREE.*\n(\n|\s)+(?=.*TREE|\z)' my_file
产品“有线结果”我不明白。
*)如何得到我想要的结果?
使用任何工具,如:pcregrep,ag,ack,sed,awk。。。
最佳答案
我想出的最简单,也可能是最愚蠢的解决方案:
[steelrat@archlinux ~]$ awk '/TREE/ {f=$0;p=1} !/^ *$/&&!/TREE/ {if (p==1) {print f; p=0} print $0}' my_file
-------- just to mark start of results ----------
^[[1;31mbla bla bla^[[0m
^[[0;36mTREE;01;^[[0m
^[[1;31m^[[0m
^[[1;31m^[[1;31mapple tree:^[[0m^[[0m
^[[1;31m4 apples^M^M^[[0m
^[[1;31m6 leafs^M^[[0m
^[[0;36mTREE;03;^[[0m
withered
^[[0;36mTREE;07;^[[0m
^[[1;31m^[[0m
^[[1;31m^[[1;31mcherry tree:^[[0m^[[0m
^[[1;31mbig branches^M^M^[[0m
^[[1;31mtchick roots^M^[[0m
^[[0;36mTREE;08;^[[0m
^[[0;36mMy tree ^[[0m I have tree house on it^[[0;31m:-)^[[0m
-------- just to mark end of results ----------
如果需要空格(需要额外的工作才能从空节中删除空格):
$ awk '/^ *$/ {print $0} /TREE/ {f=$0;p=1} !/^ *$/&&!/TREE/ {if (p==1) {print f; p=0} print $0}' my_file
-------- just to mark start of results ----------
^[[1;31mbla bla bla^[[0m
^[[0;36mTREE;01;^[[0m
^[[1;31m^[[0m
^[[1;31m^[[1;31mapple tree:^[[0m^[[0m
^[[1;31m4 apples^M^M^[[0m
^[[1;31m6 leafs^M^[[0m
^[[0;36mTREE;03;^[[0m
withered
^[[0;36mTREE;07;^[[0m
^[[1;31m^[[0m
^[[1;31m^[[1;31mcherry tree:^[[0m^[[0m
^[[1;31mbig branches^M^M^[[0m
^[[1;31mtchick roots^M^[[0m
^[[0;36mTREE;08;^[[0m
^[[0;36mMy tree ^[[0m I have tree house on it^[[0;31m:-)^[[0m
-------- just to mark end of results ----------
关于linux - 摆脱文件中多余的线条,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/39765930/