我需要在过去的20个git提交(或范围)中搜索文本"TEXT"
我需要查看我匹配的文件名和行号.
注意:
我想搜索提交内容,但不想像那样提交项目git grep
.
通过提交内容,我的意思是我可以看到使用git diff HEAD^^^..HEAD
我得到的最近的是git log --raw -GTEXT
它,它显示我在提交内容和显示文件名中包含"TEXT"的提交.但是仍然没有行号.
并且有一些管道
git diff $(git log -n 20 --pretty=format:%h -GTEXT) | grep -E 'TEXT|\+\+\+|@@\s'
它仍然有点罗嗦和很多噪音,如果你有更好的解决方案,请回答.
获取最近20次提交:
git log -n 20
Run Code Online (Sandbox Code Playgroud)
获取每个关联数组:
declare -A COMMITS # Declare associative array
COMMITNUMBER=0
while read -r line; do # For each line, do
# Add 1 to COMMITNUMBER, if the current line contains "commit [0-9a-f]* (e.g., new associative array index for each commit)
# As this'll happen straight way, our array is technically 1-indexed (starts from "${COMMITS[1]}", not "${COMMITS[0]}")
REGEX="commit\s[0-9a-f]*"
[[ "$line" =~ $REGEX ]] && COMMITNUMBER=$(( COMMITNUMBER+1 ))
# Append the commit line to the index
COMMITS[$COMMITNUMBER]="${COMMITS[$COMMITNUMBER]} $line"
done < <(git log -n 20)
Run Code Online (Sandbox Code Playgroud)
然后迭代:
for i in "${!COMMITS[@]}"
do
echo "key : $i"
echo "value: ${COMMITS[$i]}"
done
Run Code Online (Sandbox Code Playgroud)
这给出了类似的输出:
key : 1
value: commit 778f88ec8ad4f454aa5085cd0c8d51441668207c Author: Nick <nick.bull@jgregan.co.uk> Date: Sun Aug 7 11:43:24 2016 +0100 Second commit
key : 2
value: commit a38cd7b2310038af180a548c03b086717d205a61 Author: Nick <nick.bull@jgregan.co.uk> Date: Sun Aug 7 11:25:31 2016 +0100 Some commit
Run Code Online (Sandbox Code Playgroud)
现在,您可以使用grep
或任何东西在循环中搜索每个,并匹配您需要的内容:
for i in "${!COMMITS[@]}"
do
REGEX="Date:[\s]*Sun\sAug\7"
if [[ "${COMMITS[$i]}" =~ $REGEX ]]; then
echo "The following commit matched '$REGEX':"
echo "${COMMITS[$i]}"
fi
done
Run Code Online (Sandbox Code Playgroud)
共:
search_last_commits() {
[[ -z "$1" ]] && echo "Arg #1: No search pattern specified" && return 1
[[ -z "$2" ]] && echo "Arg #2: Number required for number of commits to return" && return 1
declare -A COMMITS # Declare associative array
COMMITNUMBER=0
while read -r line; do # For each line, do
# Add 1 to COMMITNUMBER, if the current line contains "commit [0-9a-f]* (e.g., new associative array index for each commit)
# As this'll happen straight way, our array is technically 1-indexed (starts from "${COMMITS[1]}", not "${COMMITS[0]}")
REGEX="commit\s[0-9a-f]*"
[[ "$line" =~ $REGEX ]] && COMMITNUMBER=$(( COMMITNUMBER+1 ))
# Append the commit line to the index
COMMITS[$COMMITNUMBER]="${COMMITS[$COMMITNUMBER]} $line"
done < <(git log -n $2)
for i in "${!COMMITS[@]}"
do
REGEX="$1"
if [[ "${COMMITS[$i]}" =~ $REGEX ]]; then
echo "The following commit matched '$REGEX':"
echo "${COMMITS[$i]}"
fi
done
}
Run Code Online (Sandbox Code Playgroud)
编辑:
用法:
search_last_commits <search-term> <last-commits-quantity>
Run Code Online (Sandbox Code Playgroud)
例:
search_last_commits "Aug" 20
Run Code Online (Sandbox Code Playgroud)