How can I replace a string in a previous command on the command-line?

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?

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

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

Method 2

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


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x