Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delete specific line from a text file?

Tags:

c#

text-files

I need to delete an exact line from a text file but I cannot for the life of me workout how to go about doing this.

Any suggestions or examples would be greatly appreciated?

Related Questions

Efficient way to delete a line from a text file (C#)

like image 410
Goober Avatar asked Aug 07 '09 14:08

Goober


People also ask

How do you delete a specific line in a file in C?

Step 1 − Read file path and line number to remove at runtime. Step 2 − Open file in read mode and store in source file. Step 3 − Create and open a temporary file in write mode and store its reference in Temporary file. Step 4 − Initialize a count = 1 to track line number.

How do I delete a specific line in vi editor?

Deleting a Line Press the Esc key to go to normal mode. Place the cursor on the line you want to delete. Type dd and hit Enter to remove the line.


2 Answers

If the line you want to delete is based on the content of the line:

string line = null; string line_to_delete = "the line i want to delete";  using (StreamReader reader = new StreamReader("C:\\input")) {     using (StreamWriter writer = new StreamWriter("C:\\output")) {         while ((line = reader.ReadLine()) != null) {             if (String.Compare(line, line_to_delete) == 0)                 continue;              writer.WriteLine(line);         }     } } 

Or if it is based on line number:

string line = null; int line_number = 0; int line_to_delete = 12;  using (StreamReader reader = new StreamReader("C:\\input")) {     using (StreamWriter writer = new StreamWriter("C:\\output")) {         while ((line = reader.ReadLine()) != null) {             line_number++;              if (line_number == line_to_delete)                 continue;              writer.WriteLine(line);         }     } } 
like image 80
Sean Bright Avatar answered Oct 19 '22 18:10

Sean Bright


The best way to do this is to open the file in text mode, read each line with ReadLine(), and then write it to a new file with WriteLine(), skipping the one line you want to delete.

There is no generic delete-a-line-from-file function, as far as I know.

like image 34
Aric TenEyck Avatar answered Oct 19 '22 18:10

Aric TenEyck