Sunday, June 5, 2022

[SOLVED] Replace string from previous command and execute

Issue

I'd like to know the shortest command for correcting a mistake in the previously executed command.

Given I executed the following command

cd /Users/USERNAME/Library/Preferences/ByHost

I would like to be able to execute a new command that takes the previous command, pipes it through grep or a similar Unix tool, and then executes. Something like this in (my admittedly uneducated) psuedo-command.

!! | xargs 's/$1/USERNAME/cirrostratus/g'

This command would execute

cd /Users/cirrostratus/Library/Preferences/ByHost

Alternately, piping a string, searching and replacing on it and executing in one line would be my second choice.


Solution

If you wanna replace a all occurences of a string (switch g) you'll need to write:

!!:gs/oldstring/newstring/

This will replace oldstring by newstring in you're last command and run them and store the result to history.

Otherwise: then syntaxe ^oldstring^newstring^ is a shortcut for:

!!:s/oldstring/newstring/

replacing only first found occurence of string.



Answered By - F. Hauri
Answer Checked By - Clifford M. (WPSolving Volunteer)