删除具有特定模式的行

时间:2013-06-20 15:35:24

标签: regex perl sed awk pattern-matching

您好我必须删除文件中的一些行:

file 1
1 2 3
4 5 6

file 2
1 2 3 6
5 7 8 7
4 5 6 9

我必须删除在文件2中找到的文件1的所有行:

output
5 7 8 7

我用了sed:

for sample_index in $(seq 1 3)
do
  sample=$(awk 'NR=='$sample_index'' file1)
  sed "/${sample}/d" file2 > tmp
done

但它不起作用。它不会打印任何东西。你知道吗?它给我错误'sed:-e expression#1,char 0:需要先例正则表达式'

3 个答案:

答案 0 :(得分:4)

这可能是一个开始:

$ grep -vf file1 file2
5 7 8 7

这里的一个潜在缺陷是,如果将5 6 9作为file1的第二行,则输出不会改变。我不确定你是否想要那个。如果没有,你可以尝试

grep -vf <(sed 's/^/^/' file1) file2

答案 1 :(得分:3)

如果您的真实数据为3列,这应该有效:

awk 'NR==FNR{a[$1$2$3]++;next}!($1$2$3 in a)' file{1,2}

对于变量列:

awk 'NR==FNR{a[$0]++;next}{for(x in a) if(index($0,x)>0) next}1' file{1,2}

答案 2 :(得分:2)

GNU的代码

sed -r 's#(.*)#/\1/d#' file1 | sed -f - file2
相关问题