How to edit a command output and execute it?

2019-09-18 11:23发布

It's possible edit a command in standard editor

But I don't found how to edit OUTPUT of command and execute it in command line. By example, if I type:

remake

I obtain:

El programa «remake» no está instalado. Puede instalarlo escribiendo: sudo apt-get install remake

I like remove de first line, and execute the second one.

This is special case because output is fron stderr instead of stout.

But in other cases is usefull edit output, add command and execute it.

3条回答
贼婆χ
2楼-- · 2019-09-18 11:53

Seeing your comment, the answer will depend on what you want to do with your output.

First of all, you have to save the output;

Extensively, you can save it in a temp file you open in vi :

TMPFILE=`mktemp`
my-command > $TMPFILE
vi $TMPFILE
// do whatever you want with $TMPFILE :
// source $TMPFILE // to execute it

which can be stored as a function

function editrun() {
    TMPFILE=`mktemp`
    "$@" > $TMPFILE 2>&1 # run the command, redirects stdout to $TMPFILE, and also stderr
    vi $TMPFILE
    source $TMPFILE
}

Then you can call

editrun my shell command with arguments

For example :

editrun echo ls -al

To get and run the command line, I used "$@". This should work in almost any situation; however, it should be possible to get the full bash command-line with some special bash variables.

查看更多
混吃等死
3楼-- · 2019-09-18 11:57

I think once you got the output, it's too late - Output is not stored anywhere. If you know your command will issue an error, you could do :

`remake 2>&1 | sed -n '2 p'`

which would execute the second line of error output (that is, sudo apt-get install remake).

Explanation :

remake
2>&1 : redirects stderr to stdout
| sed -n '2 p' : only print the second line
backquotes (``) : executes the command

But that means you know your program is not installed, so better write directly :

sudo apt-get install remake

I would rather try to intercept the "program not installed, install it " behaviour, so as to ask "install it [y/n]".

But maybe you don't know a simple trick : you can copy & paste the command just by selecting the command part (sudo apt-get install ...) with the mouse, and clicking with right or middle button (depending on the terminal emulator you use).

查看更多
女痞
4楼-- · 2019-09-18 12:04

You can use grep.

I would do it like this:

remake 2>&1 >/dev/null | grep -v -l -i "El programa «remake» no está in stalado."

Or just this:

remake 2>&1 >/dev/null | grep -l -i "Puede instalarlo escribiendo: sudo apt-get install remake"

| is a pipe, it sends command output to grep (which then filters the output) and prints stdout.

In this case, we redirect stderr (2) input to stdout (&1) to /dev/null, then we filter it with grep.

查看更多
登录 后发表回答