从另一个文件中删除包含字符串的文件中的所有行

时间:2018-11-21 02:33:24

标签: awk grep match carriage-return

我想基于匹配另一个文件中的字符串来删除文件的所有行。这是我用过的,但是只删除了一些:

watchers: {
   propertyToWatch: {
      immediate: false,
      handler: function() { //code.. }
   }
}

这是我的输入文件(inputfile.csv)中的示例行:

grep -vFf to_delete.csv inputfile.csv > output.csv

我的文件“ to_delete.csv”如下所示:

Ata,Aqu,Ama3,Abe,0.053475,0.025,0.1,0.11275,0.1,0.15,0.83377
Ata135,Aru2,Aba301,A29,0.055525,0.025,0.1,0.082825,0.075,0.125
Ata135,Atb,Aca,Am54,0.14695,0.1,0.2,0.05255,0.025,0.075,0.8005,
Adc,Aru7,Ama301,Agr84,0.002075,0,0.025,0.240075,0.2,0.

因此,具有这些字符串的任何行都应删除,在这种情况下,第1行和第3行应删除。所需输出样本:

Aqu
Aca

1 个答案:

答案 0 :(得分:3)

编辑: :由于OP的文件中包含回车符,因此现在也要为其添加解决方案。

cat -v Input_file     ##To check if carriage returns are there or not.
tr -d '\r' < Input_file > temp_file  &&  mv temp_file Input_file

由于您不清楚Input_file的样本和预期的输出,因此无法完全对其进行测试,因此,请尝试以下方法。(如果您对awk感到满意),请在代码中附加> temp_file && mv temp_file Input_file将输出保存到Input_file本身。

awk -F, 'FNR==NR{a[$0];next} {for(i=1;i<=NF;i++){if($i in a){next}}} 1'  to_delete.csv  Input_file  > temp_file  && mv temp_file  Input_file

说明: 现在也为上述代码添加了说明。

awk -F, '                          ##Setting field separator as comma here.
FNR==NR{                           ##checking condition FNR==NR which will be TRUE when first Input_file is being read.
  a[$0]                            ##Creating an array named a whose index is $0.
  next                             ##next will skip all further statements from here.
}
{
  for(i=1;i<=NF;i++){              ##Starting a for loop from value i=1 to till value of NF.
     if($i in a){                  ##checking if $i is present in array a if yes then go into this condition block.
       next                        ##next will skip all further statements(since we DO NOt want to print any matching contents)
     }                             ##Closing if block now.
  }                                ##Closing for block here.
}                                  ##Closing block which should be executed for 2nd Input_file here.
1                                  ##awk works on pattern and action method so making condition TRUE here and not mentioning any action so by default print of current line will happen.
'  to_delete.csv  Input_file       ##Mentioning Input_file names here now.