How to keep matching and not matching grep

I use grep very often and am familiar with it being able to return the corresponding lines (by default) and inconsistent lines (using the -v option). However, I want to be able to grep the file once to separate line matching and non-matching.

If this is not possible, let me know. I understand that I can do this easily in perl or awk, but curious if this is possible with grep.

Thanks!

+4
source share
3 answers

If it should NOT be grep - this is a one-time split based on the pattern - found pattern> file1 pattern not found> file2

awk '/pattern/ {print $0 > "file1"; next}{print $0 > "file2"}' inputfile 
+6
source

I had exactly the same problem, and I wrote a small Perl script [1] for this. It takes only one argument: regex to enter grep input.

[1] https://gist.github.com/tonejito/c9c0bffd75d8c81483f9107c609439e1

It reads STDIN line by line and compares with the given regex , matching lines go into STDOUT , but do not match - STDERR .

I did it this way because this tool is in the middle of the pipeline, and I use shell redirection to save the files in their final location.

+1
source

Step 1: read the file

Step 2. Replace the spaces with a new line and save the result in a temporary file

Step 3: Get only lines containing '_' from the temporary file and save it in multiwords.txt

Step 4. Exclude lines containing "-" from the temporary file, then save the result in singlewords.txt

Step 5. Delete the temporary file

  cat file | tr ' ' '\n' > tmp.txt | grep '_' tmp.txt > multiwords.txt | grep -v '_' tmp.txt > singlewords.txt | find . -type f -name 'tmp.txt' -delete 
0
source

All Articles