Replace a String in a File with Nodejs

Replace a string in a file with nodejs

You could use simple regex:

var result = fileAsString.replace(/string to be replaced/g, 'replacement');

So...

var fs = require('fs')
fs.readFile(someFile, 'utf8', function (err,data) {
if (err) {
return console.log(err);
}
var result = data.replace(/string to be replaced/g, 'replacement');

fs.writeFile(someFile, result, 'utf8', function (err) {
if (err) return console.log(err);
});
});

Replace multiple strings in a file using nodejs

You need to do the second replace on the result of the first replace. data isn't changed by replace; replace returns a new string with the change.

So:

var result = data.replace(/{{Name}}/g, 'abc')
.replace(/{{Address}}/g, 'xyz');

...then write result to the file.

Alternately, and this particularly useful if it's a large file or you have lots of different things to replace, use a single replace with a callback:

var replacements = Object.assign(Object.create(null), {
"{{Name}}": "abc",
"{{Address}}": "xyz"
// ...and so on...
});

var result = data.replace(/{{[^}]+}}/g, function(m) {
return replacements[m] || m;
});

Or with a Map:

var replacements = new Map([
["{{Name}}", "abc"],
["{{Address}}", "xyz"]
// ...and so on...
]);

var result = data.replace(/{{[^}]+}}/g, function(m) {
return replacements.get(m) || m;
});

Replace multiple strings in a text file with one string using javascript

to add to the previous replies, you can use capture groups to back reference parts of the matched text i.e.

if you search for "user"

let newText = yourText.replace(/^((\"user\")(:".*")(.*))$/gm, '"removed"$3$4' );

if you search for "1232"

let newText = yourText.replace(/^((\".*\")(:"1232")(.*))$/gm, '"removed"$3$4' );

nodejs - replace a string everywhere in a large file

After going through a lot of answers, this worked for me which took care of the required synchronous and asynchronous behaviour, large file and keeping the name same.

function format_file(fileName) {
return new Promise((resolve, reject) => {
if (fs.existsSync(fileName)) {
var fields = fileName.split('/');
var tempFile = "";
var arrayLength = fields.length;
for (var i = 0; i < arrayLength - 1; i++) {
tempFile = tempFile + fields[i] + "/";

}
tempFile = tempFile + "tempFile" + fields[arrayLength - 1];
console.log("tempfile name is : " + tempFile + " actualFileName is :" + fileName);
var processStream = new ProcessStream();
fs.createReadStream(fileName, { bufferSize: 128 * 4096 })
.pipe(processStream)
.pipe(fs.createWriteStream(tempFile)).on('finish', function() { // finished
fs.renameSync(tempFile, fileName);
console.log('done encrypting');
resolve('done');
});
} else {
reject('path not found')
}
});
}

Replace different strings in file from an object in nodejs

Try this, this will replace all the content from file and then write the update content back.

fs.readFile('myfile.txt', 'utf8', (readErr, data) => {
if(readErr) {
return console.log(readErr);
} else {
for (var key in obj){
let re = new RegExp(`(?<=config.${key} = ).*(?=)`, 'g');
data = data.replace(re, `'${obj[key]}'`);
}
fs.writeFile('myfile.txt', data, 'utf8', (writeErr) => {
if(writeErr) {
return console.log(writeErr);
} else {
console.log('File was writen');
}
});
}
});

Replace string in a text file in node.js

If a template engine is overkill just use string.replace().

temp = "Hello %NAME%, would you like some %DRINK%?";

temp = temp.replace("%NAME%","Michael Dillon");
temp = temp.replace("%DRINK%","tea");
console.log(temp);

With only a bit more work you could make a general purpose template function based on just the standard methods in the String object.

Replace a line in txt file using JavaScript

This should do it

var fs = require('fs')
fs.readFile(someFile, 'utf8', function (err,data) {

var formatted = data.replace(/This is the old line/g, 'This new line replaces the old line');

fs.writeFile(someFile, formatted, 'utf8', function (err) {
if (err) return console.log(err);
});
});

Stream edit text file and replace string with increments

Combining sed and bash, would you please try the following:

#!/bin/bash

# show usage on improper arguments
usage() {
echo "usage: $1 filename.md number"
exit 1
}

file=$1 # obtain filename
[[ -n $file ]] || usage "$0" # filename is not specified
num=$2 || usage "$0" # obtain end bumber
(( num > 0 )) || usage "$0" # number is not specified or illegal

for (( i = 1; i <= num; i++ )); do
new="${file%.md}$i.md" # new filename with the serial number
cp -p -- "$file" "$new" # duplicate the file
sed -i "s/_INCREMENT_/$i/" "$new"
# replace "_INCREMENT_" with the serial number
done

Save the script above as a file generate or whatever, then run:

bash generate post.md 2


Related Topics



Leave a reply



Submit