【问题标题】:Diff consecutive lines unixdiff连续行unix
【发布时间】:2015-08-25 23:48:39
【问题描述】:

我有一棵扁平线的树,例如:

a<1 and b<1 and c<1 then result=1
a<1 and b>1 and d<1 then result=2
a<1 and b>1 and d>1 then result=3

我想打印删除与前一行匹配的每个连续行的子字符串 例如,结果将是:

a<1 and b<1 and c<1 then result=1
        b>1 and d<1 then result=2
                d>1 then result=3

本质上,前一行和当前行之间的共同元素不会再次打印 -> 只打印两行之间的差异。

有人可以帮忙吗?

【问题讨论】:

  • 必须在外壳中?你已经尝试过什么?

标签: linux unix binary-tree diff


【解决方案1】:

替代方案,使用字段作为匹配单元,具有最终输出格式

awk 'NR==1{w=length($0)} 
     {sep=line=""; 
      for(i=1;i<=NF;i++) 
        if(p[i]!=$i) 
          for(j=i;j<=NF;j++) {
             p[j]=$j; 
             line=line sep $j;
             sep=OFS
          } 
         printf "%"w"s\n", line
      }' diffs

a<1 and b<1 and c<1 then result=1
        b>1 and d<1 then result=2
                d>1 then result=3

【讨论】:

  • 选择第一行作为宽度会导致数据的扩展版本出现一些有趣的格式(我很想在每一行上使用w=length($0)),但除此之外,OP 要求.
  • 是的,这假设“树”的根是第一行。也许预先扫描文件以获得最大长度是更好的解决方案。
  • 我在一个较长的测试文件上运行了您的代码,得到了一些两位数的结果。它与代码产生了一些有趣的对齐方式——只差一个字符,因为我的行长变化这么大。
  • 我使用的附加数据是:a=1 and b&lt;1 and c&lt;1 then result=4 a=1 and b=1 and c=1 then result=5 a=1 and b=1 and c&gt;1 then result=6 a=1 and b&gt;1 and c&lt;1 then result=7 a=1 and b&gt;1 and c=1 then result=8 a=1 and b&gt;1 and c&gt;1 then result=9 a&gt;1 and b&lt;1 and c&lt;1 then result=10 a&gt;1 and b&lt;1 and c=1 then result=11 a&gt;1 and b&lt;1 and c&gt;1 then result=12 a&gt;1 and b=1 and c&lt;1 then result=13 a&gt;1 and b=1 and c=1 then result=14 a&gt;1 and b=1 and c&gt;1 then result=15 a&gt;1 and b&gt;1 and c&lt;1 then result=16 a&gt;1 and b&gt;1 and c=1 then result=0 a&gt;1 and b&gt;1 and c&gt;1 then result=22。您可以将某些结果更改为 3 位数。
【解决方案2】:
awk '{for (i=1;i<=length($0); i++) 
    if (substr($0,i,1)!=substr(a,i,1)) {printf "%s",substr($0,i,1);a=""}
      else printf " ";
    printf "\n"
    a=$0}'

产量

a<1 and b<1 and c<1 then result=1
         >1 and d<1 then result=2
                 >1 then result=3

即上一行和当前行之间的公共字符不再打印

如果您需要发布的结果,您可以拆分您的行以形成标记,并将这些标记与前一行的标记进行比较。您可以打印令牌或必要的空格来获取身份。

【讨论】:

  • 不完全清楚应该从第二行删除b 还是从第三行删除d;我觉得这有点太热情了。
  • 因此我在结果下写了文字。它适合从前一行中删除匹配子字符串的请求,但不适合示例。这就是为什么我提到了基于令牌的方法,我没有详细说明......
猜你喜欢
  • 2020-07-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-03-13
  • 2018-09-16
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多