和大多数开发人员一样,我整天都在搜索和阅读源代码。就我个人而言,我一直不习惯集成开发环境 (IDE),多年来,我主要使用 grep 并复制/粘贴文件名来打开 Vi(m)。
最终,我想出了这个脚本,并根据需要慢慢改进它。
它的依赖项是 Vim 和 rlwrap,并且它是根据 Apache 2.0 许可开源的。要使用该脚本,将其放在你的 PATH 中,并在包含文本文件的目录中运行它
grepgitvi <grep options> <grep/vim search pattern>
它将返回一个编号的搜索结果列表,提示你输入要使用的结果的编号,并使用该结果打开 Vim。在你退出 Vim 后,它将再次显示该列表,循环直到你输入除结果编号之外的任何内容。你还可以使用向上和向下箭头键来选择文件;这(对我来说)更容易找到我已经看过的结果。
与现代 IDE 相比,甚至与 Vim 的更复杂用法相比,它简单而原始,但这就是我所需要的工作方式。
脚本
#!/bin/bash
# grepgitvi - grep source files, interactively open vim on results
# Doesn't really have to do much with git, other than ignoring .git
#
# Copyright Yedidyah Bar David 2019
#
# SPDX-License-Identifier: Apache-2.0
#
# Requires vim and rlwrap
#
# Usage: grepgitvi <grep options> <grep/vim pattern>
#
TMPD=$(mktemp -d /tmp/grepgitvi.XXXXXX)
UNCOLORED=${TMPD}/uncolored
COLORED=${TMPD}/colored
RLHIST=${TMPD}/readline-history
[ -z "${DIRS}" ] && DIRS=.
cleanup() {
rm -rf "${TMPD}"
}
trap cleanup 0
find ${DIRS} -iname .git -prune -o \! -iname "*.min.css*" -type f -print0 > ${TMPD}/allfiles
cat ${TMPD}/allfiles | xargs -0 grep --color=always -n -H "$@" > $COLORED
cat ${TMPD}/allfiles | xargs -0 grep -n -H "$@" > $UNCOLORED
max=`cat $UNCOLORED | wc -l`
pat="${@: -1}"
inp=''
while true; do
echo "============================ grep results ==============================="
cat $COLORED | nl
echo "============================ grep results ==============================="
prompt="Enter a number between 1 and $max or anything else to quit: "
inp=$(rlwrap -H $RLHIST bash -c "read -p \"$prompt\" inp; echo \$inp")
if ! echo "$inp" | grep -q '^[0-9][0-9]*$' || [ "$inp" -gt "$max" ]; then
break
fi
filename=$(cat $UNCOLORED | awk -F: "NR==$inp"' {print $1}')
linenum=$(cat $UNCOLORED | awk -F: "NR==$inp"' {print $2-1}')
vim +:"$linenum" +"norm zz" +/"${pat}" "$filename"
done
2 条评论