Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove one line from a txt file

Tags:

I have the following text file ("test.txt") that I want to manipulate in node.js:

world food 

I want to remove the first line so that food becomes the first line instead. How can I do that?

like image 633
Alta istar Avatar asked Aug 09 '16 05:08

Alta istar


People also ask

How do I delete a single line?

Click the line, connector, or shape that you want to delete, and then press Delete. Tip: If you want to delete multiple lines or connectors, select the first line, press and hold Ctrl while you select the other lines, and then press Delete.

How do you remove a single line from a text file in Unix?

To delete a line, we'll use the sed “d” command. Note that you have to declare which line to delete. Otherwise, sed will delete all the lines.

How do you delete a single line from a text file in C++?

open("temp. txt"); cout << "Which line do you want to remove? "; cin >> deleteline; while (getline(fin,line)) { if (line != deleteline) { temp << line << endl; } } temp.


2 Answers

var fs = require('fs') fs.readFile(filename, 'utf8', function(err, data) {     if (err)     {         // check and handle err     }     // data is the file contents as a single unified string     // .split('\n') splits it at each new-line character and all splits are aggregated into an array (i.e. turns it into an array of lines)     // .slice(1) returns a view into that array starting at the second entry from the front (i.e. the first element, but slice is zero-indexed so the "first" is really the "second")     // .join() takes that array and re-concatenates it into a string     var linesExceptFirst = data.split('\n').slice(1).join('\n');     fs.writeFile(filename, linesExceptFirst, function(err, data) { if (err) {/** check and handle err */} }); }); 
like image 86
Scott M Avatar answered Sep 22 '22 00:09

Scott M


I just came across the need to be able to exclude several lines in a file. Here's how I did it with a simple node function.

const fs = require('fs');  const removeLines = (data, lines = []) => {     return data         .split('\n')         .filter((val, idx) => lines.indexOf(idx) === -1)         .join('\n'); }  fs.readFile(fileName, 'utf8', (err, data) => {     if (err) throw err;      // remove the first line and the 5th and 6th lines in the file     fs.writeFile(fileName, removeLines(data, [0, 4, 5]), 'utf8', function(err) {         if (err) throw err;         console.log("the lines have been removed.");     }); }) 
like image 42
Kevin O'Hara Avatar answered Sep 21 '22 00:09

Kevin O'Hara