簡體   English   中英

在文件中找到特定文本字符串后的5行的grep

[英]Grep for the 5 lines after a specific text string found in files

我有很多Java文件,我想找到我們通過多少次日志記錄

logger.isDebugEnabled(){
    logger.Debug("some debug message");
}

為了了解我們可能多久使用一次isDebugEnabled函數。 我發現了我們通過/調用的次數

grep -r "isDebugEnabled" --include=*.java . | wc -l

但我想知道其中有多少行語句。 有沒有人有一個很好的腳本來搜索此內容或以最有效的方式進行搜索的任何想法?

不要為此使用grep,請使用以下AWK程序:

prev ~ /isDebugEnabled/ && $0 ~ /logger\.Debug\("[^"]"\)/ {
    print FILENAME ":" NR ": " $0
}
{
    prev = $0
}

該程序會記住prev變量中的前一行,從而允許您一次比較兩行。

要實際使用它,請編寫:

find . -name '*.java' -print \
| xargs awk 'prev ~ /isDebugEnabled/ && /logger\.Debug\("[^"]"\)/ { print FILENAME ":" NR ": " $0 } { prev = $0 }'

如注釋中所述,grep提供了在匹配之后和匹配之前打印一定數量行的選項。

要在匹配后打印行:

grep -A 2 "string to match" file.txt 

要在匹配之前打印行:

grep -B 2 "string to match" file.txt

在嘗試編寫給出最終答案的腳本之前,請嘗試其他方法以了解最適合您想要的內容。 測試一個文件。 您是否認為logger.Debug("The database has ", getDbNum(), "and the server has ", getRemoteNumSpecial(), "records."); 是一個簡單的單行嗎?
您可以為第一個方向收集一些數字。 下面的示例使用x.java作為示例源文件。

# Nr of isDebugEnabled calls
grep -c "logger.isDebugEnabled" x.java
# Some may be comment with //
grep -c "//.*logger.isDebugEnabled" x.java
# How much debug-lines
grep -c "logger.Debug" x.java
# How much debug-lines with more than 1 parameter (having a ,)
grep -c "logger.Debug.*," x.java
# How much debug-lines without the closing ) on the same line
grep "logger.Debug" x.java | grep -v "Debug.*)"
# How much logger.isDebugEnabled() without a logger.Debug on the next line
grep -A1 "logger.isDebugEnabled" x.java | grep -c "logger.Debug"
# How much logger.Debug a "}" on the next line
# The debugline might have a }, so skip lines with logger.Debug 
grep -A1 "logger.Debug" x.java | grep -v "logger.Debug" | grep -c "}"

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM