1

echo $'one\ntwo\nthree' | grep -F -v $(echo three$'\n'one)

Output should in theory be the string two

I've read that the -F command lets grep interpret each line as a list connected by 'or' qualifier.

Tom
  • 919
  • 3
  • 9
  • 22
  • The below might help you http://stackoverflow.com/questions/152708/how-can-i-search-for-a-multiline-pattern-in-a-file – Saravanakumar Vadivel Apr 20 '16 at 23:51
  • It's not a perl regular expression though. It's a shell expansion. This would normally work with -F -f if it were a file, however I'm treating a shell expansion as if it were a fileoutput, and in theory that should work with just the -F statement but it doesn't – Tom Apr 21 '16 at 00:00
  • Is this some sort of glob? – Laurel Apr 21 '16 at 00:41
  • I dont think it qualifies as a glob. But I can tell you that instead of `echo three$'\n'one`, it will be a `cat patterns.txt | cut -f 1`. I have terms in a column of a file that I wish to excise out with cat and cut, then pass that into grep. Those terms are the pattern I really want. I can save it as a file, but I want to learn the method that just lets me take that output and expand it in the shell – Tom Apr 21 '16 at 00:52

1 Answers1

2

Only mistake is some missing double-quotes:

echo $'one\ntwo\nthree' | grep -F -v "$(echo three$'\n'one)"

Also, keep in mind that this will also filter out "threesome", "someone", etc...

(@etan-reisner points out that running set -x before the original and the fixed command can be used to observe the difference the double-quotes make here, and, more generally, is a useful way to debug bash commands.)

webb
  • 4,180
  • 1
  • 17
  • 26
  • Incredible. I would never think of this. What's going on here with the double quotes? – Tom Apr 21 '16 at 00:54
  • Answering why requires someone more knowledgeable than I, but adding double quotes in shell is often a reasonable fix to try. – webb Apr 21 '16 at 00:56
  • 1
    from what I know, I would speculate that its inputting the whole expansion in quotes interprets it as as one string. Otherwise, it would be interpreted as separated commands fields. Hence, why the error message says it failed to find a directory. It's interpreting subsequent lines as a directory to look into – Tom Apr 21 '16 at 01:05
  • 1
    @Tom Run `set -x` before running the original command and the working command and you'll see the difference. Also, having indicated in your post that your command was generating an error and posting it would have been a good idea. – Etan Reisner Apr 21 '16 at 01:41
  • Im having some trouble understanding what you mean. Run set -x, then first comand, then second? – Tom Apr 22 '16 at 18:03