1

I have a list of strings and want to find and delete lines containing these strings in a file. A short example of the list of strings is listed as below.

File S

1Mo 32,33
2Mo 7,26
2Mo 7,27
2Mo 7,28

And a short example of the file is as follows.

File A

1Mo 32,33 I love you.
2Mo 7,26  I like you.
Hi 1,2  This is not so fun.
Ab 3,4  I am stupid.

My expected output is like this:

Hi 1,2  This is not so fun.
Ab 3,4  I am stupid.

I tried to use the following command, unfortunately I failed:

grep -f file S  file A|awk '{print $0}'

I searched the related question, but most of them focus on deleting the line with one specific pattern. I Does anybody know how to deal with this issue? Thx.

  • Try with grep -vf file\ S file\ A – don_crissti Nov 21 '15 at 18:49
  • @don_crissti it works, many thx!!! – Frown Nov 21 '15 at 19:08
  • If there's any chance that your strings could contain a regular expression metacharacter, it is necessary to also use -F. – Barefoot IO Mar 4 '16 at 23:26
1

In AWK, the code would be:

NR == FNR {
    line[$0]++;
    next;
}
!line[$1" "$2]

As an one liner:

awk 'NR == FNR {line[$0]++; next;} !line[$1" "$2]' file_S file_A
1
$ grep -vF -f file_S file_A
Hi 1,2  This is not so fun.
Ab 3,4  I am stupid.

This uses the strings in file_S to get the lines in file_A that does not contain any of those strings.

-v inverts the sense of the matching so that lines without a match are passed through, and -F tells grep to treat the strings as fixed string and not like regular expressions.

-3
awk -F "|" '{if($1 != "1Mo") if($1 != "2Mo" ) { print $0;}}' inputFile > OutputFile
  • 1
    Snippet sharing for copy-paste is not a very HQ communication... – peterh Feb 1 '18 at 14:05
  • This answer could be made much more useful by editing it to explain in detail how it works. – dhag Feb 1 '18 at 14:20
  • You mean you're going to add a new if-statement for each line in the first file? – Kusalananda Feb 1 '18 at 14:45

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.