【问题标题】:Filter out rows from column A based on values in column B根据 B 列中的值过滤掉 A 列中的行
【发布时间】:2022-01-03 07:06:54
【问题描述】:

我有一个包含两列的 CSV 文件。第一列是所有订阅者的列表,第二列是需要从邮件中排除的订阅者列表:

all,exclusions
alice@example.com,charles@example.com
bill@example.com,alice@example.com
charles@example.com
daisy@example.com
esther@example.com

我需要输出第一列中未列在第二列中的所有订阅者。所需的输出是这样的:

bill@example.com
daisy@example.com
esther@example.com

到目前为止,我只有这个:

awk -F, '(NR>1) {if($1!=$2) {print}}' subs.csv

这当然只会在同一行的两列中都有匹配值时过滤掉这些行。 感谢您的帮助。

【问题讨论】:

标签: awk


【解决方案1】:

使用数组。我假设第一列中没有重复项。

awk -F ',' 'NR>1{
              array[$1]++; array[$2]--
            }
            END{
              for(i in array){ if(array[i]==1){ print i } }
            }' file

一行:

awk -F ',' 'NR>1{ array[$1]++; array[$2]-- } END{for(i in array){ if(array[i]==1){ print i } } }' file

输出:

esther@example.com daisy@example.com bill@example.com

【讨论】:

    【解决方案2】:

    为了完整起见,删除排除的条目,包括重复值。

    数据

    $ cat file
    all,exclusions
    alice@example.com,charles@example.com
    bill@example.com,alice@example.com
    charles@example.com
    daisy@example.com
    daisy@example.com,alice@example.com
    daisy@example.com,charles@example.com
    daisy@example.com
    esther@example.com
    esther@example.com
    alice@example.com
    
    $ awk -F ',' 'NR>1 && NF==1{ all[$1]++ }
      NR>1 && NF==2{ all[$1]++; excl[$2]++ }
      END{ for(i in excl){ all[i]=0 };
        for(i in all){ if(all[i]>=1){ print i } } }' file
    
    esther@example.com
    daisy@example.com
    bill@example.com
    

    【讨论】:

      【解决方案3】:

      有两个数组。第一个字段$1list of all subscribers,它用作名为a 的数组的索引。第二个字段$2list of subscribers who need to be excluded,它用作数组b 的索引。我们在END 部分以这种方式得到subscribers from first column who are not listed in the second columnfor (i in a) if (!(i in b)) print i 使用两个数组:

      awk -v FS=',' '
              NR > 1 {a[$1];b[$2]}
              END{for (i in a) if (!(i in b)) print i}
      ' file
      esther@example.com
      daisy@example.com
      bill@example.com
      

      或者使用导致下一次迭代开始的continue 语句。

      awk -v FS=',' '
              NR > 1 {a[$1];b[$2]}
              END{for (i in a) if (i in b) continue;else print i}
      ' file
      esther@example.com
      daisy@example.com
      bill@example.com 
      

      【讨论】:

        猜你喜欢
        • 2018-01-16
        • 1970-01-01
        • 2022-12-09
        • 1970-01-01
        • 1970-01-01
        • 2018-08-06
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多