LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - Software (https://www.linuxquestions.org/questions/linux-software-2/)
-   -   Search and replace strings with file paths in vim (https://www.linuxquestions.org/questions/linux-software-2/search-and-replace-strings-with-file-paths-in-vim-4175532456/)

geeksquads 01-29-2015 11:43 PM

Search and replace strings with file paths in vim
 
Hello all,

I have a config file containing file paths.
I am wondering how one would go about searching and replacing the strings in vim.

Here is an excerpt of my file I am modifying in vim, so you guys can get a better idea about the situation:
Code:

Host america
    IdentityFile ~/.ssh/id_rsa.local
Host germany
    IdentityFile ~/.ssh/id_rsa.local
Host canada
    IdentityFile ~/.ssh/id_rsa.local
Host japan
    IdentityFile ~/.ssh/id_rsa.local
Host amsterdam
    IdentityFile ~/.ssh/id_rsa.local
[...]

I understand the the general format for a [s]ubstitute is:
Code:

:%s/<search string>/<replacement string>/g
I want to replace the line with the file path, so naturally I tried:
Code:

:%s,IdentityFile ~/.ssh/id_rsa.local,this is a test,gc
I changed the delimiter to ",", so that I wouldn't have to mess with correctly escaping the slashes.
After executing the command, vim unfortunately comes back with a "E486: Pattern not found: IdentityFile ~/.ssh/id_rsa.local" result. This is certainly not correct, since we can see the string is in the file above.

I assume that I need to escape something else, but I am not sure what or how. Can anyone shed some light on this issue?

Thanks!

veerain 01-30-2015 12:42 AM

Quote:

:%s,IdentityFile ~/.ssh/id_rsa.local,this is a test,gc
There is an error in your vim regex. You should escape '~' character.

Try instead:

Code:

:%s,IdentityFile \~/.ssh/id_rsa.local,this is a test,gc

geeksquads 01-30-2015 02:03 AM

Hi veerain,

I can't believe I didn't try that. I was thinking it was going to be a lot more complicated.
I totally thought it would be an issue related with something regarding "." or something. I guess not.

It works now. Thanks again, veerain!

----

On a sidenote, after looking up what "~" actually means, it seems to be a backreference to a previous substitute string. As to how you actually use it is beyond me... If anyone is in the mood to add more details about it, I'd love to learn a bit more.


All times are GMT -5. The time now is 06:20 AM.