Tôi thấy chủ đề này hữu ích - vì vậy tôi nghĩ rằng tôi sẽ thêm câu trả lời cho vấn đề của riêng mình.
Tôi muốn chỉnh sửa tệp cấu hình cơ sở dữ liệu (datastax cassandra) từ ứng dụng nút trong javascript và đối với một trong các cài đặt trong tệp mà tôi cần khớp trên một chuỗi và sau đó thay thế dòng theo sau nó.
Đây là giải pháp của tôi.
dse_cassandra_yaml='/etc/dse/cassandra/cassandra.yaml'
// a) find the searchString and grab all text on the following line to it
// b) replace all next line text with a newString supplied to function
// note - leaves searchString text untouched
function replaceStringNextLine(file, searchString, newString) {
fs.readFile(file, 'utf-8', function(err, data){
if (err) throw err;
// need to use double escape '\\' when putting regex in strings !
var re = "\\s+(\\-\\s(.*)?)(?:\\s|$)";
var myRegExp = new RegExp(searchString + re, "g");
var match = myRegExp.exec(data);
var replaceThis = match[1];
var writeString = data.replace(replaceThis, newString);
fs.writeFile(file, writeString, 'utf-8', function (err) {
if (err) throw err;
console.log(file + ' updated');
});
});
}
searchString = "data_file_directories:"
newString = "- /mnt/cassandra/data"
replaceStringNextLine(dse_cassandra_yaml, searchString, newString );
Sau khi chạy, nó sẽ thay đổi cài đặt thư mục dữ liệu hiện có thành cài đặt mới:
tập tin cấu hình trước:
data_file_directories:
- /var/lib/cassandra/data
tập tin cấu hình sau:
data_file_directories:
- /mnt/cassandra/data
value
một biến?