【问题标题】:how to remove all lines containg less than n number of items如何删除包含少于n个项目的所有行
【发布时间】:2011-07-29 09:54:29
【问题描述】:

我想删除包含少于 n 个项目的所有行,以空格分隔。

假设我想删除包含少于 3 个项目的行。所以下面的文件:

sdf sdfsdf sdfgsdf sdfsdfsd
sdf sdfsdf 
sdf sdfsdf sdfgsdf 
sdf sdfsdf sdfgsdf  ertert

应该导致:

sdf sdfsdf sdfgsdf sdfsdfsd
sdf sdfsdf sdfgsdf 
sdf sdfsdf sdfgsdf  ertert

其实awksed 两种方案都可以接受。

【问题讨论】:

    标签: vim sed awk vi


    【解决方案1】:

    这个怎么样:

    awk 'NF >= 3' filename
    

    【讨论】:

    • 如果你有数字作为外壳值:awk -v n=$num 'NF>=n' file
    • 我想过添加它,但我认为越简单越好。不过,谢谢,让我的回答更完整。
    【解决方案2】:

    在 vim 中:

    :v/\(\S\+\s\+\)\{3,}/d
    

    另一种选择是

    :g/./exec len(split(getline('.'))) < 3 ? 'd' : ''
    

    你也可以做一些有趣的事情,比如

    :py vim.current.buffer[:] = [l for l in vim.current.buffer if len(l.split()) >= 3]
    

    【讨论】:

      【解决方案3】:

      由于有vim标签:

      :v/\(\S\+\s\)\{2,}\S/d
      

      将 2 替换为 n-1。

      【讨论】:

        【解决方案4】:

        我知道你要求 vi 解决方案,但这在 perl 中非常简单:

        ethan@rover:~$ perl -ne 'print if split > 3' foo
        

        其中“foo”是您的文件。

        【讨论】:

        • 非常适合 MJB。在这种情况下,awk 比 Perl 更合适。
        【解决方案5】:

        NF 是记录中的字段数。用你想要的数字替换 2

        awk '{if (NF > 2) print $0}' inputFile.txt
        

        【讨论】:

          【解决方案6】:
          ~$ cat test.txt | awk '{if(length($3) > 0) print $0;}'
          

          希望对你有帮助

          【讨论】:

            猜你喜欢
            • 2013-03-07
            • 2016-12-16
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2012-06-14
            • 1970-01-01
            相关资源
            最近更新 更多