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?
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.
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.
open("temp. txt"); cout << "Which line do you want to remove? "; cin >> deleteline; while (getline(fin,line)) { if (line != deleteline) { temp << line << endl; } } temp.
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 */} }); });
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."); }); })
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With