nEJ*_*EJC 4 bash command-line grep file
I'm doing a simple grep for lines starting with some patteren like:
grep -E "^AAA" myfile > newfile
Run Code Online (Sandbox Code Playgroud)
我还想(同时)将那些不匹配的行重定向到另一个文件。
我知道可以简单地做两次并在第二次尝试中使用-v,但是文件(相对)很大,只读取一次会节省一些非常宝贵的时间......
我正在考虑将不匹配重定向到 stderr 的一些事情,例如:
grep -E -magic_switch "^AAA" myfile > newfile 2> newfile.nonmatch
Run Code Online (Sandbox Code Playgroud)
这个技巧是否可以用grep还是我应该只编码它?
(可能有额外的价值 - 我在 bash 脚本中编码)
这将起作用:
awk '/pattern/ {print; next} {print > "/dev/stderr"}' inputfile
Run Code Online (Sandbox Code Playgroud)
或者
awk -v matchfile=/path/to/file1 -v nomatchfile=/path/to/file2 '/pattern/ {print > matchfile; next} {print > nomatchfile}' inputfile
Run Code Online (Sandbox Code Playgroud)
或者
#!/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
}
Run Code Online (Sandbox Code Playgroud)
像这样调用最后一个:
./script.awk regex outputfile1 outputfile2 inputfile
Run Code Online (Sandbox Code Playgroud)