Tech Kraft

Documentum, AWS, Java, Ruby on Rails, Linux, Windows, App Servers


Linux: vi search and replace command

Format

The format of the command is given below:

%s/<string_being_replaced>/<replacement_string>/

Examples

In order to replace the word “hate” with “love”.

  • Open the file in vi
  • Hit [Esc] (Esc in vi lets you type commands instead of typing content)
  • Type : (colon) followed by %s/hate/love/ and hit [Enter] key.
:%s/hate/love/

Above command will replace first occurrence of word hate with love on all lines. The % represents all lines.

To replace all occurrences of word hate with love on all lines, use the g option (g stands for global, indicating all occurrences).

:%s/hate/love/g

You can replace g with a number 1,2,…N to change only the n’th occurrence on each line.
Use find and replace on line ranges (match by line numbers)

You can also make changes on range of lines i.e. replace first occurrence of hate with love on lines 5 through 20 only, enter:

:5,20s/hate/love/

Following command will replace first occurrence of hate with love starting at the current line for the next 100 lines:

:.,+100s/hate/love/

Word Match

You can match by words i.e. find the next line containing a word “test”, then replace all occurrences of hate with love:

:/test/s/hate/love/g

To specify ranges:

:/test/,/guest/s/hate/love/g


Leave a comment

About Me

Senior Software Engineer professional with over 16 years of success with multiple open source technologies and various Content Management platforms and solutions.

Proven technical abilities through numerous projects involving enterprise web application design and development, application installation, configuration and support, and workflow and collaboration system designs.

  • Ability to learn new technologies and platforms quickly and apply them to the task at hand.
  • Excellent analytical skills, and strong communication and collaboration abilities.
  • Technical emphasis in including but not limited to Java, Ruby on Rails, Documentum and Alfresco
    in both Linux and Windows based environments

Newsletter