newfile I would als...">

Grep redirect mismatch

I am making simple grep for lines starting with some patteren, such as:

grep -E "^AAA" myfile > newfile

I would also like (in the same vein) to redirect those irrelevant lines to another file.
I know that one could just do it twice and use -v in the second attempt, but the files are (relatively) huge, and only reading them once will save some pretty valuable time ...

I thought something along the line of inconsistency redirection to stderr like:

grep -E -magic_switch "^AAA" myfile > newfile 2> newfile.nonmatch

Is this trick somehow with grep , or should I just code it?

(there may be an extra value - I encode this in a bash script)

+3
source share
5

:

awk '/pattern/ {print; next} {print > "/dev/stderr"}' inputfile

awk -v matchfile=/path/to/file1 -v nomatchfile=/path/to/file2 '/pattern/ {print > matchfile; next} {print > nomatchfile}' inputfile

#!/usr/bin/awk -f
BEGIN {
    pattern     = ARGV[1]
    matchfile   = ARGV[2]
    nomatchfile = ARGV[3]
    for (i=1; i<=3; i++) delete ARGV[i]
}

$0 ~ pattern {
    print > matchfile
    next
}

{
    print > nomatchfile
}

:

./script.awk regex outputfile1 outputfile2 inputfile
+4

, . Perl - :

if (/^AAA/) {
   print STDOUT $_;
}
else
{
   print STDERR $_;
}
+2

, grep, Perl:

#! /usr/bin/perl
# usage: script regexp match_file nomatch_file < input

my $regexp = shift;
open(MATCH, ">".shift);
open(NOMATCH, ">".shift);

while(<STDIN>) {
    if (/$regexp/o) {
        print MATCH $_;
    } else {
        print NOMATCH $_;
    }
}

Python, :

#! /usr/bin/python
# usage: script regexp match_file nomatch_file < input

import sys
import re

exp = re.compile(sys.argv[1])
match = open(sys.argv[2], "w")
nomatch = open(sys.argv[3], "w")

for line in sys.stdin:
    if exp.match(line): match.write(line)
    else:               nomatch.write(line)

( . . , .)

+2

:

function perg {
  awk '{y = $0~z ? "out" : "err"; print > "/dev/std" y}' z="$1" "$2"
}

perg ^AAA myfile > newfile 2> newfile.nonmatch

cat myfile | perg ^AAA > newfile 2> newfile.nonmatch
0

( https://unix.stackexchange.com/a/71511). , .

- :

cat file.txt | tee >(grep 'pattern' > matches.txt) | grep -v 'pattern' > non-matches.txt

0

Source: https://habr.com/ru/post/1787984/


All Articles