LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - General (https://www.linuxquestions.org/questions/linux-general-1/)
-   -   Replacing multiple instances of text within a file using vi editor (https://www.linuxquestions.org/questions/linux-general-1/replacing-multiple-instances-of-text-within-a-file-using-vi-editor-4175557966/)

kaplan71 11-04-2015 10:50 AM

Replacing multiple instances of text within a file using vi editor
 
Hello --

I need to replace multiple instances in a give file of the following text:

Quote:

/usr/lib/nagios/plugins
with the following text:

Quote:

/usr/local/nagios/libexec
Can this be done in vi editor, and if so, what is the correct command sequence?

If vi editor is not the preferred method, what would be a better way?

Thanks.

Sefyir 11-04-2015 11:17 AM

Probably something like

Code:

:s/\/usr\/lib\/nagios\/plugins/\/usr\/local\/nagios\/libexec/g
Without escapes for /

Code:

:%s//usr/lib/nagios/plugins//usr/local/nagios/libexec/g

suicidaleggroll 11-04-2015 11:38 AM

In general, string replacement in vi is:
Code:

:%s/oldstring/newstring/g
Since your strings include forward slashes, you'll need to delimit them so they don't interfere with the string replacement syntax.

rtmistler 11-04-2015 12:01 PM

My preferred method would be just to use sed, and the command is still the same. Never thought of it, but sed and vi may be common code in that respect.

kaplan71 11-04-2015 12:47 PM

Hello --

I tried both expressions, vi and sed, but without success.

When I try the vi command syntax:

Quote:

:%s//usr/lib/nagios/plugins/usr/local/nagios/libexec/g
I get the error message:

Quote:

E488: Trailing characters
When I enter the follow sed command syntax:

Quote:

sed 's/usr/libexec/nagios/plugins/usr/local/nagios/libexec/' checkcommands.cfg
The error message is as follows:

Quote:

sed: -e expression #1, char 15: unknown option to `s'
Where are my syntaces mistaken?

rtmistler 11-04-2015 12:52 PM

You have to delimit similar to how Sefyir shows you.

You can experiment with using double quotes. I'm unsure if they work, I know in naming files and referring to them in commands like cp and mv, using double quotes around filenames which have spaces works. But also delimiting the spaces with a backslash before them works too. Similarly, everywhere you have a forward slash which is just supposed to be a forward slash you need to delimit with a backslash before it.

Any chance you can just use gedit or emacs? For me emacs, providing you have the display capabilities to support an emacs buffer window just works fine for global search and replace. You don't need regular expression formats because the editor recognizes you are within search and replace mode. I'm assuming gedit is similar to that.

chrism01 11-04-2015 04:50 PM

Just use an alternate delimiter (same as sed can)
Code:

:s:/usr/lib/nagios/plugins:/usr/local/nagios/libexec:g


All times are GMT -5. The time now is 03:36 AM.