首页 > 解决方案 > 打印第一列不在列表中的行

问题描述

我有一个文件中的数字列表

cat to_delete.txt
2
3
6
9
11

和一个文件夹中的许多txt文件。每个文件都有制表符分隔的行(可以比这更多的行)。

3 0.55667 0.66778 0.54321 0.12345
6 0.99999 0.44444 0.55555 0.66666
7 0.33333 0.34567 0.56789 0.34543

我想删除第一个数字(awk 的 $1)在 to_delete.txt 中的行,并只打印第一个数字不在 to_delete.txt 中的行。更改应该是替换旧文件。

预期产出

7 0.33333 0.34567 0.56789 0.34543

这是我到目前为止得到的,它没有删除任何东西;

for file in *.txt; do awk '$1 != /2|3|6|9|11/' "$file" > "$tmp" && mv "$tmp" "$file"; done

我在这里查看了很多类似的问题,但仍然无法使其发挥作用。我也试过 grep -v -f to_delete.txt 和 sed -n -i '/$to_delete/!p'

任何帮助表示赞赏。谢谢!

标签: bash

解决方案


在 awk 中:

$ awk 'NR==FNR{a[$1];next}!($1 in a)' delete file

输出:

7 0.33333 0.34567 0.56789 0.34543

解释:

$ awk '
NR==FNR {       # hash records in delete file to a hash
    a[$1]       
    next
}
!($1 in a)      # if $1 not found in record in files after the first, output
' delete files*   # mind the file order

推荐阅读