1

I'm looking for a way to delete certain lines in a file taking patterns from external file. The best way would be to use sed. I was trying several articles, like this, but they doesn't answer my task.

Say i have a text.file with:

Adam
Belle
Candy
Donald
Eve

And a pattern.file has:

Don*
Candy

With grep -fv pattern.file text.file i get exactly what i want, but only in view:

Adam
Belle
Eve

I cannot redirect the filtered output to a new file. Therefore, i need a way to be able modify the original text.file, deleting all the rows that match the pattern(s) from external file.

In my real usecase the text.file contains non-alphabethical order, not always capitalized, so creating a generic regex for 'sed' is not possible.

What would be the best approach to pass patterns for lines deletion from an external file?

4
  • Why can't you redirect the output to a new file? sed -i creates a new file behind the scenes, anyway.
    – choroba
    Nov 17, 2018 at 20:05
  • @choroba - loss of privileges. Can only modify
    – faceless
    Nov 17, 2018 at 20:14
  • 1
    So maybe sponge, to redirect the output to the same file. Nov 17, 2018 at 20:16
  • 1
    This might work: grep -vf pattern.file text.file >foo; cp foo text.file & rm foo
    – Cyrus
    Nov 18, 2018 at 8:44

2 Answers 2

1

With GNU sed and bash:

sed -i -f <(sed 's|.*|/&/d|' pattern.file) text.file
2
  • This sort-of works, but not necessarily for the right reasons.  (1) It does an unanchored match, so if the pattern file contains "Alex", it will remove "Alexander" and "Alexandra" from the text file. (2) It expects the patterns to be regular expressions. It does not look like this is what the OP intended. For example, for the given pattern file, "Douglass" would be deleted, because Don* matches any line that contains Do. (If it happens to be followed by a string of n’s, that doesn’t matter.) (3) The user should be warned that, if the pattern file contains slashes (/), this will fail. Nov 18, 2018 at 9:20
  • Thanks @Cyrus, this is what i was looking for! Scott, thatnk you as well, the provided answer suits my particular pattern management, but i will take your notes in attention.
    – faceless
    Nov 18, 2018 at 9:41
0

Taking your example would have been easier to do:

grep -fv pattern.file text.file > output.txt

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.