【问题标题】:How to remove a column of lines if it had a word如果有一列有单词,如何删除它
【发布时间】:2017-02-14 22:52:41
【问题描述】:

如果搜索关键字存在于该列中,我想删除该行中的一个列。

我的输入将是多行输入,比如列分隔符是:

:I want to remove a : column in the line : if the search key word exists within : that column
:I will : be using : word as : the key word
:colon will : be used : as the : delimiter

搜索关键字是word

我的输出应该是

:I want to remove a : column in the line : that column:
:I will : be using :
:colon will : be used : as the : delimiter

【问题讨论】:

  • 与以前的版本相比,您的输入行不以: 结尾。这实际上变成了一个新问题。考虑也将: 添加到此版本中,如果您是,请提出一个新问题无法修改解决方案
  • 还提到是否需要删除与搜索关键字匹配的所有列或仅第一个匹配项

标签: bash perl shell awk sed


【解决方案1】:

示例输入:

echo $x
:I want to remove a : column in the line : if the search key word exists within : that column:

awk解决方案:

 echo $x |awk -v RS=":" -v ORS=:  '!/word/'
:I want to remove a : column in the line : that column:

解释:

使用RS作为“:”,将使awk认为每条记录都用“:”分隔。然后打印不包含关键字word的记录,然后保持输出记录用“:”分隔。

【讨论】:

  • 这很好,最适合我的要求。感谢您的帮助。
  • 我尝试了多行输入,只要搜索关键字在最后一列中,下一行就会附加到修改后的行。有什么办法可以在换行符中保留下一行。
  • @VijeshKk 修改您的问题以包含多行输入文件和预期输出是个好主意...
  • 我同意 Sundeep,需要示例输入来修改我们的命令。
【解决方案2】:
$ cat ip.txt 
:I want to remove a : column in the line : if the search key word exists within : that column:

$ sed 's/:[^:]*word[^:]*//' ip.txt
:I want to remove a : column in the line : that column:
  • :[^:]* 表示 : 后跟零个或多个非: 字符
  • word 要匹配的字符串
  • [^:]* 零个或多个非: 字符
  • 由于替换为空,匹配的字符串被有效删除
  • 请注意,这只会删除第一个这样的匹配项

【讨论】:

    【解决方案3】:

    Perl 解决方案:

    use strict;
    use warnings;
    
    my $data=':I want to remove a : column in the line : if the search key word exists within : that column:';
    
    my @cols = split(/:/,$data);
    
    foreach my $cols(@cols) {
        if($cols ne "" && $cols !~ /word/) { #search keyword
            print ":",$cols #print other than search key word
        }
    }
    print ":\n";
    

    【讨论】:

      【解决方案4】:

      Perl 代码:

      my $data="
      :I want to remove a : column in the line : if the search key word exists within : that column
      :I will : be using : word as : the key word
      :colon will : be used : as the : delimiter";
      
      print $data,"\n";
      
      $data=~s/:[^:]*word[^:]*//mgi;
      
      print $data,"\n";
      

      【讨论】:

        猜你喜欢
        • 2023-03-22
        • 1970-01-01
        • 1970-01-01
        • 2021-10-03
        • 1970-01-01
        • 2022-06-21
        • 1970-01-01
        • 1970-01-01
        • 2019-12-14
        相关资源
        最近更新 更多