我正在尝试在我的 shell 上创建一个宏。
我试图自动化的操作是这样的:
Find all the files containing TEXT_TO_SEARCH, and open them with VSCODE
我可以用一行字来做到这一点
$ code `git grep TEXT_TO_SEARCH | cut -d: -f1 | sort -u`
所以我的第一步是将以下函数添加到
~/.zshrc
cgrep() {
code `git grep "$1" | cut -d: -f1 | sort -u`
}
然后
$ cgrep TEXT_TO_SEARCH
这有效。
现在我正在尝试添加一个额外的功能:
Before opening each file with VSCode, echo to the console "Opening FILE_NAME"
我首先尝试过这个
cgrep() {
grep_results=`git grep "$1" | cut -d: -f1 | sort -u`
for file in $grep_results; do
echo "Opening $file"
code $file
done
}
请注意,
grep_results
是一个“垂直列表”,即
$ echo $grep_results
src/path1/FILE1.py
src/path2/FILE2.py
src/path3/FILE3.py
这样,for 循环会将第一个
file
视为整体 grep_results
,并打开 FILE3.py
(而不是 src/path3/FILE3.py
)。
我也尝试过这个(在 GPT 的帮助下)
cgrep() {
grep_results=`git grep "$1" | cut -d: -f1 | sort -u`
echo "$grep_results" | while read -r file; do
echo "Opening $file"
code "$file"
done
}
这样我可以只打开第一个 grep 文件,然后我从 VSCode 收到一条我不想要的消息,但我实际上并不理解
$ cgrep TEXT_TO_SEARCH
Opening src/path1/FILE1.py
Run with 'code -' to read from stdin (e.g. 'ps aux | grep code | code -').
在 Unix&Linux StackExchange 中的 Gilles 'SO-别再作恶'的帮助下解决了(他的完整答案这里)。
这是我的最终版本
cgrep() {
grep_results=(`git grep -l $1`)
for file in "${grep_results[@]}"; do
echo "Opening $file"
code $file
done
}