
我經常需要在 Bash 中完整複製輸出行:
$ grep -ilr mysql_connect *
httpdocs/includes/config.php
httpdocs/admin/db.php
statistics/logs/error_log
$ vim httpdocs/includes/config.php
有什麼方法可以設定 Bash 或 Tmux 快捷方式three lines up
,例如@@3
:
$ grep -ilr mysql_connect *
httpdocs/includes/config.php
httpdocs/admin/db.php
statistics/logs/error_log
$ vim @@3 # This would be the equivalent of vim httpdocs/includes/config.php (three lines up)
快捷方式不需要是@@
,其他任何東西都可以。理想情況下,這可以在任何 Bash 中工作,但 tmux 快捷方式也可以工作。
請注意,我熟悉 tmux 和螢幕複製和貼上(進入貼上模式,移動到複製,返回,貼上),但我希望有一些我可以更容易使用的東西(@@N),因為我似乎經常這樣做。
答案1
以下 Bash 函數將使用執行命令(即grep -ilr mysql_connect *
)後獲得的輸出來建立一個列表,您可以從中選擇一個選項(檔案)。選擇後,將使用 Vim 開啟該檔案。
output_selection()
{
local i=-1;
local opts=()
local s=
while read -r line; do
opts+=("$line")
printf "[$((++i))] %s\n" "$line"
done < <("$@")
read -p '#?' s
if [[ $s = *[!0-9]* ]]; then
printf '%s\n' "'$s' is not numeric." >&2
elif (( s < 0 )) || (( s >= ${#opts[@]} )); then
printf '%s\n' "'$s' is out of bounds." >&2
else
vim "${opts[$s]}"
fi
}
前提條件: 輸出必須以“\n”分隔。
用法: 輸出選擇 [指令]
例子:
output_selection grep '.php$' foo.txt
這並不完全是您所要求的,因此您可以將其視為以 IMO 更方便的方式執行相同任務的合理建議 - 特別是當輸出很大時。
答案2
假設檔案名稱不包含空格,這將滿足您的要求:
$ set -- $(grep -ilr mysql_connect * | tac)
$ echo $3
httpdocs/includes/config.php
$ echo $2
httpdocs/admin/db.php
$ echo $1
statistics/logs/error_log
您可以建立其他函數,而無需| tac
以正確的順序列印它:
$ set -- $(grep -ilr mysql_connect *)
$ echo $1
httpdocs/includes/config.php
$ echo $2
httpdocs/admin/db.php
$ echo $3
statistics/logs/error_log