Monday, August 26, 2013

Deleting all lines that contain specific data


Q: On the UNIX systems, how do I delete every line in a file that has the word "outdated" in it?
A: The two easiest ways are using the grep -v command at the UNIX prompt or the ex/vi g and d commands.



Using grep -v

The UNIX grep command lets you search for a string in one or more files. The "-v" option tells grep to display lines that do not have the information you tell it to search for.
grep -v outdated myfile > myfile.new
This example looks for the text "outdated" in the file named "myfile". But since you included the "-v" option, it displays the lines that do not have "outdated" in them. Using UNIX's redirection symbol and another file name tells the system to put the lines in that file.To summarize: this command searches the file "myfile" for the text "outdated", and puts all lines that do not have "outdated" in them into the file "myfile.new".
grep -iv outdated myfile > myfile.new
By adding the "-i" option, you tell grep to ignore the case of the text "outdated".This command searches the file "myfile" for the text "outdated"--no matter whether upper-case or lower-case letters have been used--and puts all lines that do not have "outdated" in them into the file "myfile.new".
grep -iv "out dated" myfile.new > myfile.newer
In this example, we tell grep to look for "out dated"--with the space in the middle.This command searches the file "myfile.new" for the text "out dated"--no matter whether upper-case or lower-case letters have been used--and puts all lines that do not have "out dated" in them into the file "myfile.newer".



Using vi global commands

Using vi, you can issue global commands from command mode. If you are not sure of the case used, you can issue this command from vi command mode before you make the global change::set ic
(set ignorecase)

:g/outdated/d
This command tells vi to do a global search for "outdated" and to delete any line containing that text.
:g/out dated/d
This command tells vi to do a global search for "out dated" and to delete any line containing that text--including the space.