shortcut to replace all strings in previous bash c

2019-05-13 18:17发布

man bash describes a very useful Event Designator

^string1^string2^

Quick substitution. Repeat the last command, replacing string1 with string2. Equivalent to ''!!:s/string1/string2/''

Is there a way to execute !!:gs/string1/string2/ when typing in @string1@string2@ on the command line to replace all occurrences in the previous command? (@ or any other designated character/string)

2条回答
【Aperson】
2楼-- · 2019-05-13 18:41
三岁会撩人
3楼-- · 2019-05-13 18:51

Shortly: no!

In fact, there may exist a way, using `trap "..." debug'...

Something like:

trap 'if [[ $BASH_COMMAND =~ ^@(.*)@(.*)@$ ]] ;then
     BASH_LAST=${BASH_LAST//${BASH_REMATCH[1]}/${BASH_REMATCH[2]}};
     $BASH_LAST;
     unset BASH_COMMAND;
   else BASH_LAST=$BASH_COMMAND;
   fi;
 ' debug

This is quick and dirty, there left an execution error, but I think: It may be a way to do it.

Edit 01

This is a little better, but history stay quite wrong:

shopt -s extdebug
trap '
    if [[ $BASH_COMMAND =~ ^@(.*)@(.*)@$ ]] ;then
        BASH_LAST="${BASH_LAST//${BASH_REMATCH[1]}/${BASH_REMATCH[2]}}"
        $BASH_LAST
        false
      else
        BASH_LAST="$BASH_COMMAND"
      fi' debug

But warn: I do this for fun, for playing with and to understand how it work... This is not intended to be used in effective final solution!!

查看更多
登录 后发表回答