2

I've got a text file, and I want to search for lines that have search_string but do not have exclude_string.

In terminal, the following gives me the output I want:

grep "search_string" | grep -v "\(exclude_string_A\|exclude_string_B\)"

I have a bash script which scans text files for particular issues (mostly using grep and sed), and I'd like to add this search to it, but I can't seem to make it work. It doesn't seem like the output of the first grep command is being used as the input for the second.

For example, for a file containing:

Gary: yes, that's what I said.  
Paul: well, I didn't hear you.  
Gary: okay, let's go.  

In the bash script, the relevant line is:

grep "Gary:" | grep -v "\(said\|told\)" $1

But the output file contains for that section:

Paul: well, I didn't hear you.  
Gary: okay, let's go.

I hope there's something simple I'm missing here!

3

Your idea is right, but your input file/string argument is in the wrong place. It should have been written as

grep "Gary:" "$1" | grep -v "\(said\|told\)"

which means apply the first grep expression to match all the lines containing Gary and filter lines containing the words said or told.

With your attempt, since run with a pipeline, both the grep processes start, but the part after | processes the input $1 as if it were a file instead of getting input from standard input over from the pipe and prints the couple of lines you are seeing.

But at this time, you are seeing the terminal hanging because the first grep is still waiting for input on its standard input stream, but it is not seeing one. Pressing the Ctrl-C sends the SIGINT signal which kills the pipeline eventually.

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.