35

I need to run a command, and then run the same command again with just one string changed.

For example, I run the command

$ ./myscript.sh xxx.xxx.xxx.xxx:8080/code -c code1 -t query

Now from there, without going back in the command history (via the up arrow), I need to replace code1 with mycode or some other string.

Can it be done in Bash?

AdminBee
  • 22,803
Raja G
  • 5,937
  • Why do you need it? – choroba Nov 16 '15 at 13:44
  • may the url contain other b ? – lese Nov 16 '15 at 13:44
  • Can you please clarify how you get the initial string in input. From your post it seems it is on your terminal likewise you typed it as a command – lese Nov 16 '15 at 14:03
  • Raja... a variation of echo http://xxx.xxx.xxx.xxx/a/b/b/c/d/e | sed 's/b/c/g'? Please tell what do you want to do, execute a command,call a program that will reach that url, change a variable value...?!? – Hastur Nov 16 '15 at 14:15
  • See https://unix.stackexchange.com/questions/116623/xy-unix-trick-for-all-instances-in-last-command for fc-s. – Hans Ginzel Sep 03 '20 at 13:46

2 Answers2

81

I renamed your script, but here's an option:

$ ./myscript.sh xxx.xxx.xxx.xxx:8080/code -c code1 -t query

after executing the script, use:

$ ^code1^code2

... which results in:

./myscript.sh xxx.xxx.xxx.xxx:8080/code -c code2 -t query

man bash and search for "Event Designators":

^string1^string2^

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

Editing to add global replacement, which I learned just now from @slm's answer at https://unix.stackexchange.com/a/116626/117549:

$ !!:gs/string1/string2

which says:

!! - recall the last command
g - perform the substitution over the whole line
s/string1/string2 - replace string1 with string2
Jeff Schaller
  • 67,283
  • 35
  • 116
  • 255
6

The bash builtin command fc can be used to find a command in the history and optionally edit/run it. Use the bash builtin help fc for more documentation.

fc -s code1=code2

Will find the all occurrences of code1 in the last command and change it to code2, then execute the new command.

It can be useful when multiple special characters need to be changed. Suppose the previous command was;

$ java a/b/c/d

Then,

fc -s /=.

will produce

$ java a.b.c.d

  • Sometimes taking a little bit more time to add an explanation and where to find further information, will change an difficult answer to understand into something easier to read/understand and adds value to the set of answers. – X Tian Oct 18 '21 at 17:02