Sed

grep:顯示文件名一次,然後顯示帶有行號的上下文

  • April 2, 2022

我們的原始碼中散佈著錯誤程式碼。使用 grep 很容易找到它們,但我想要一個find_code可以執行的 bash 函式(例如。find_code ####),它將提供以下幾行的輸出:

/home/user/path/to/source.c

85     imagine this is code
86     this is more code
87     {
88         nicely indented
89         errorCode = 1111
90         that's the line that matched!
91         ok this block is ending
92     }
93 }

這是我目前擁有的:

find_code()
{
   # "= " included to avoid matching unrelated number series
   # SRCDIR is environment variable, parent dir of all of projects
   FILENAME= grep -r "= ${1}" ${SRCDIR}
   echo ${FILENAME}
   grep -A5 -B5 -r "= ${1}" ${SRCDIR} | sed -e 's/.*\.c\[-:]//g'
}

問題:

1)這不提供行號

  1. 它只匹配 .c 源文件。我無法讓 sed 匹配 .c、.cs、.cpp 和其他源文件。但是,我們確實使用了 C,因此只需匹配 - 或 :(grep 在每行程式碼之前附加到文件名的字元)匹配object->pointers並搞砸一切。

我會改變一些事情。

find_code() { 
   # assign all arguments (not just the first ${1}) to MATCH
   # so find_code can be used with multiple arguments:
   #    find_code errorCode
   #    find_code = 1111
   #    find_code errorCode = 1111
   MATCH="$@" 

   # For each file that has a match in it (note I use `-l` to get just the file name
   # that matches, and not the display of the matching part) I.e we get an output of:
   #
   #       srcdir/matching_file.c
   # NOT:
   #       srcdir/matching_file.c:       errorCode = 1111
   #
   grep -lr "$MATCH" ${SRCDIR} | while read file 
   do 
       # echo the filename
       echo ${file}
       # and grep the match in that file (this time using `-h` to suppress the 
       # display of the filename that actually matched, and `-n` to display the 
       # line numbers)
       grep -nh -A5 -B5 "$MATCH" "${file}"
   done 
}

引用自:https://unix.stackexchange.com/questions/86180