3

I need to replace a word in line or URL but I need to do it from command line/terminal.

I mean

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

Now from there, without going back, I need to replace code1 with mycode or some other string.

  • 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
18

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
  • Hi , I have been through some case. Here it is.` mv /server/logfile1 /nfs/logs/ && gzip /nfs/logs/logfile1 & ` and after that I did ^logfile1^logfile2 but changes applied at only 1st match but not globally at gzip place. Please help. Thank you. – rɑːdʒɑ Nov 20 '15 at 14:12
  • @Raja I have updated the answer with global search & replace – Jeff Schaller Nov 20 '15 at 17:52
  • 2
    Of course you use !! to repeat the previous command in its entirety, unaltered, but almost anything that begins with !!: can be shortened to !:; e.g., !:gs/string1/string2. – G-Man Jan 21 '16 at 19:48
  • 2
    The ^ syntax works in zsh as well. Just documenting for posterity. – Kevin Suttle Jun 23 '17 at 19:24
  • 2
    ^foo^bar^:G for global search and replace. – HappyFace Sep 3 '18 at 10:48

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.