How to save both matching and non-matching from grep

試著忘記壹切 提交于 2019-12-04 01:37:02

问题


I use grep very often and am familiar with it's ability to return matching lines (by default) and non-matching lines (using the -v parameter). However, I want to be able to grep a file once to separate matching and non-matching lines.

If this is not possible, please let me know. I realize I could do this easily in perl or awk, but am curious if it is possible with grep.

Thanks!


回答1:


If it does NOT have to be grep - this is a single pass split based on a pattern -- pattern found > file1 pattern not found > file2

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



回答2:


I had the exact same problem and I wrote a small Perl script for that [1]. It only accepts one argument: the regex to grep input on.

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

It reads STDIN by line and checks against the given regex, matched lines go to STDOUT and not matched go to STDERR.

I made it this way because this tool sits in the middle of a pipeline and I use shell redirection to save the files on their final location.




回答3:


Step 1 : Read the file

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

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

Step 4 : Exclude the lines that contains '-' from the temporary file then save the result into 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


来源:https://stackoverflow.com/questions/15789228/how-to-save-both-matching-and-non-matching-from-grep

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!