
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 *
) を実行した後に得られる出力を使用して、1 つのオプション (ファイル) を選択できるリストを作成します。選択後、ファイルは 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
これはまさにあなたが求めていたものではありませんが、特に出力が大きい場合には、同じタスクを私見ではより便利な方法で実行するための正当な提案として見ることができます。
答え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