Friday, May 3, 2013

Vi editor: Delete matched search pattern from a file

1) How can I search for a word and delete that matched word in vi editor?

This is bit tricky question. With SED its bit easy to do. In vi editor too we can search for a word and delete it with some trick.

Delete matched search term from a file

Step1: Go to command mode and search mode

Step2: Now search for your term and replace it with nothing

:%s/searchterm//g

This will help you to delete all the occurrences of your search term. Let me explain above syntax

:%s is for searching for entire file, if you want to search in a particular line we can just use :s.
/serchterm// will replace 'searchterm' with nothing, which means it will be removed from that line
g for global removal, what it mean is the search and replace operation is applicable for all the occurrences of search-term in a given line.

Delete matched search term line from a file 

Some times its require to delete entire line of your searched term. We can use below code once you go to command mode

:g/searchterm/d

Deleting reverse or inverse of search term lines from a file


We can even delete all the lines which do not contain our search term with below code.

:g!/searchterm/d

Hope this helps, check our other vi editor posts as well.

0 comments:

Post a Comment