【问题标题】:Delete certain rows in text files using UNIX使用 UNIX 删除文本文件中的某些行
【发布时间】:2013-11-08 13:32:33
【问题描述】:

我有一堆需要清理的文本文件。我使用的是 UNIX bash,所以 AWK 或 grep 都不错。

文本文件看起来像这样:

1766 1789  
1764 1790  
1762 1849  
0  
1357 1817  
1366 1857  
0  
360 42  
352 95  
0  
293 142  
302 181  
delete-this  
0  
302 181   
0  

我想要的是删除所有带有“0”的行,“delete-this”,只有一行两列或三行两列。

结果应该是这样的:

1766 1789    
1762 1849   
1357 1817  
1366 1857    
360 42  
352 95    
293 142  
302 181 

非常感谢!

更多信息:第 1 行第 2 列和第 2 行第 2 列之和应大于 1,否则必须删除第 2 行。

【问题讨论】:

  • 您的示例输出中缺少一些行。为什么1764 1790 消失了?另外,only one row with two columns or three rows with two columns 是什么意思?
  • 前三行应该只有两行!因为第 1 行第 2 列和第 2 行第 1 列的差异 = 1。
  • 所以你只想匹配被0s包围的2/3行块。

标签: unix awk grep


【解决方案1】:

这是一个难题,或者难以理解,但我们又来了:

awk '/[0-9]+ [0-9]+/ {a[++t]=$0;b[t]=$2;next} {if (t>=2) for (i=1;i<=t;i++) {if (b[i]-c!=1) print a[i];c=b[i]};t=0}'
1766 1789
1762 1849
1357 1817
1366 1857
360 42
352 95
293 142
302 181

它是如何工作的:

awk '
    /[0-9]+ [0-9]+/ {               # if line does have 2 column of number, then 
        a[++t]=$0                   # add line to array "a" and increment variable "t"
        b[t]=$2                     # add column 2 to array "b"
        next                        # go to next line
        }

        {
        if (t>=2)                   # is there more two or more lines with numbers connrected, then
            for (i=1;i<=t;i++) {    # loop trough array "a" with all numbers
                if (b[i]-c!=1)      # test if the difference between this number in column 2 is more than 1 compare to previous line
                    print a[i]      # then print array "a"
                    c=b[i]          # store array "b" information in variable "b"
                }
            ;t=0                    # clear counter "t"
        }' file

【讨论】:

  • 非常好!但是如何删除单行和三行呢?
  • 我的错!这是相同的行,所以我很困惑。都很好!! :)
  • 现在它应该符合一切。如果没问题,接受它:)
  • 确实非常好! :) 谢谢!
  • 这是迄今为止我见过的最精彩的事情......哇。我希望我有技能!
猜你喜欢
  • 2016-05-12
  • 1970-01-01
  • 1970-01-01
  • 2023-03-23
  • 2016-03-03
  • 2019-10-18
  • 2014-04-19
  • 1970-01-01
  • 2011-09-27
相关资源
最近更新 更多