[
{
“filePath”: “relative/path/to/your/file1.txt”,
“findText”: “line 1 to findnline 2 to find”,
“replaceText”: “line 1 to replacenline 2 to replace”
},
{
“filePath”: “relative/path/to/your/file2.txt”,
“findText”: “line 1 to find 2nline 2 to find 2”,
“replaceText”: “line 1 to replace 2nline 2 to replace 2”
}
]
const fs = require(‘fs’);
const path = require(‘path’);
// Leer el archivo JSON que contiene las configuraciones
const config = JSON.parse(fs.readFileSync(‘config.json’, ‘utf8’));
config.forEach((task) => {
const filePath = path.resolve(__dirname, task.filePath);
// Leer el contenido del archivo
fs.readFile(filePath, 'utf8', (err, data) => {
if (err) {
console.error(`Error reading file ${filePath}:`, err);
return;
}
// Reemplazar el texto encontrado con el nuevo texto
const updatedData = data.replace(new RegExp(task.findText, 'g'), task.replaceText);
// Escribir el contenido actualizado de vuelta al archivo
fs.writeFile(filePath, updatedData, 'utf8', (err) => {
if (err) {
console.error(`Error writing file ${filePath}:`, err);
return;
}
console.log(`File ${filePath} has been updated.`);
});
});
});
Quiero mejorar el script
Kevin Manuel Chinte Hidalgo is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.