6

Let's say I have FileA.txt which looks a bit like this:

43287134, string1, string2
1233, foo, bar
973, barfoo, foobar
7464, asdf, ghjk

And I've got FileB.txt with these regexes, separated by a line:

^973,
^1233,

I would like to apply FileB.txt regexes onto FileA.txt, and delete the lines that match so that final result would be:

43287134, string1, string2
7464, asdf, ghjk

Is there any tool available to do this? Thanks!

1
  • 1
    Just to clarify, you want to delete only lines that match any the regexes in the file. This is a different problem from deleting or keeping lines that match 2 or more regexes from a large set of patterns. (i.e. where a single line has to match multiple regexes). Your title is confusing. Jan 7 '18 at 2:23
11

This is exactly what grep is designed for:

grep -v -f FileB.txt FileA.txt
  • -f <filename> reads regexes from the file (instead of command line)
  • -v reverse the match (prints non-matching lines)

Output:

43287134, string1, string2
7464, asdf, ghjk
0
1

This can also be done with sed:

while read -r REG_EX; do sed -i "/$REG_EX/d" FileA.txt; done<FileB.txt
6
  • won't work due to first ^ character in fileB.txt -bash-4.4$ while read -r REG_EX; do sed -i "/$REG_EX/d" toto ; done < titi -bash-4.4$ as you see no output :) to avoid that you can try sed without -i but you will get as number of outputs as number of line from fileB like that : -bash-4.4$ while read -r REG_EX; do sed "/$REG_EX/d" toto ; done < titi 43287134, string1, string2 7464, asdf, ghjk 43287134, string1, string2 7464, asdf, ghjk -bash-4.4$
    – francois P
    Jan 7 '18 at 0:10
  • 1
    @francoisP: What OS are you running? On my mac I have to use sed -i.bak... but it does work. Also there should be no output. It doesn't produce output with -i it just modifies the file.
    – jesse_b
    Jan 7 '18 at 0:53
  • tryied on both linux and BSD it's similar/same
    – francois P
    Jan 7 '18 at 10:53
  • 1
    @francoisP: Have you checked your toto file to see if it's been modified? As I said above this command should not produce any output to STDOUT.
    – jesse_b
    Jan 7 '18 at 14:22
  • I always test in real before posting . of course with -i it is ok to get no output but infile result is same double results ...
    – francois P
    Jan 7 '18 at 14:28

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.