1

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.

Benjamin W.
  • 46,058
  • 19
  • 106
  • 116
james_womack
  • 10,028
  • 6
  • 55
  • 74
  • Choose `USER_NAME` or `USERNAME` but be consistent. `grep` is for finding text; `sed` is for changing text; `awk` can be used for changing text but is arguably overkill for the scenario. Would you expect the `cd /Users/USER_NAME/Library/Preferences/ByHost` command to succeed? `cd` is a built-in command which complicates things in some respects. Why don't you just `cd ~cirrostratus/Library/Preferences/ByHost`? Does: `cd $(echo $_ | sed 's/USERNAME/cirrostratus/')` do the job for you? – Jonathan Leffler Apr 30 '13 at 05:15
  • In a script, or on the command line? – tripleee Apr 30 '13 at 05:15
  • @tripleee in the command line por favor. – james_womack Apr 30 '13 at 05:33
  • Jonathan, using `cd` was just a meaningless example—I know it's built in, it's the first command I learned as a kid. I execute commands in zsh or bash thousands of times each week and a micro-optimization of quickly correcting mistakes I just made in a previous command would help me over time, and just feel cleaner IMO than moving my cursor over to correct the mistake. `cd $(echo $_ | sed 's/USERNAME/cirrostratus/')` doesn't work in this case because my goal is to correct mistakes (typos, bad copy paste etc.). Thx for the info re: grep not replacing text. – james_womack Apr 30 '13 at 05:41
  • You could take a look at this answer: http://stackoverflow.com/a/16284715/1765658 – F. Hauri - Give Up GitHub Apr 30 '13 at 06:50

1 Answers1

5

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.

F. Hauri - Give Up GitHub
  • 64,122
  • 17
  • 116
  • 137