Bash – Reference prior command output / terminal screen contents in current command line

bash

I often need to copy an output line in Bash in its entirety:

$ grep -ilr mysql_connect *
httpdocs/includes/config.php
httpdocs/admin/db.php
statistics/logs/error_log
$ vim httpdocs/includes/config.php

Is there any way to configure a Bash or Tmux shortcut for three lines up, like perhaps @@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)

The shortcut does not need to be @@, anything else would do. Ideally this would work in any Bash, but a tmux shortcut would work too.

Note that I am familiar with tmux and screen copy and paste (enter paste mode, move to copy, come back, paste), but I am hoping for something that I could use easier (@@N) as I seem to do this often.

Best Answer

The following Bash function will use the output you get after running the command (i.e. grep -ilr mysql_connect * ) to create a list from which you can select one option, a file. After selection is made, the file will be opened using 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
}

Preconditions: The output must be '\n' delimited.

Usage: output_selection [command]

Example:

output_selection grep '.php$' foo.txt

This is not exactly what you asked for, so you can see that as a legitimate suggestion to perform the same task in a way that is, IMO, more convenient - especially when the output is large.