grep: search once for different pattern and output to several files

浪尽此生 提交于 2020-01-15 20:33:24

问题


Is it possible to tell grep to use different output files for every type of matching search string?

I need to search all *.log recursively to find all "[ERROR]", "[WARN]" and "[ASSERT]". But I would like to have it separated in different output files. One output file for each search string. (without calling grep several times!)

searching already works: (called from gmake)

grep -nHr --include=*.log -e '\[ERROR\]' -e '\[WARN\]' -e '\[ASSERT\]' $(root_path) > $(root_path)/result.txt

But due to performance I do not want to call grep several times:

grep -nHr --include=*.log -e '\[ERROR\]' $(root_path) > $(root_path)/result_[ERROR].txt

grep -nHr --include=*.log -e '\[WARN\]' $(root_path) > $(root_path)/result_[WARN].txt

Is it possible to have it somehow like:

grep -nHr --include=*.log -e {'PATTERN1' | 'PATTERN2' | 'PATTERN3'} $(root_path) > $(root_path)/result{'PATTERN1'|'PATTERN2'|'PATTERN3'}.txt

回答1:


To read thru the file in 1 pass, and write to multiple outFiles, I would use awk

  awk '/^\[Error\]/ {print FILENAME ":" NR ":" $0 > "errorFile.txt" }
       /^\[Warn\]/ {print FILENAME ":" NR ":" $0 > "warnFile.txt" }
       /Assert/ {print FILENAME ":" NR ":" $0 > "assertFile.txt" }'  logFile

You can gain a minor increase in speed, if you know for certain that the Error/Warn/Assert tokens are always the first on the line of interest and use the beginning-of-line reg-exp char (^), ie.

/^Error/ {print $0 > "errorFile.txt" 



回答2:


 sed -n '{
/\[ERROR\]/w errorlog
/\[WARN\]/w warnlog
/\[ASSERT\]/w assertlog
}' $(  find /your/path/here -type f -name "*.log" )

may work for you.



来源:https://stackoverflow.com/questions/34184036/grep-search-once-for-different-pattern-and-output-to-several-files

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