[英]What is wrong with this simple concatenation
我只是想使用Node.js將文本文件中的幾行文本連接起來。 結果和預期結果如下所示,並不相同。 我不確定為什么要得到我要得到的結果,它似乎覆蓋了前一行。
目標:連接行和同一行中的以下子項
app.js
'use strict'
const fs = require('fs')
let targetRegex = /Line.*/;
let concatStatement = '';
fs.readFileSync('input.txt').toString().split('\n')
.forEach(function (line) {
if (targetRegex.test(line)) {
concatStatement = line;
}
else {
concatStatement += line
console.log(concatStatement);
}
});
input.txt中
Line11
SubA
Line22
SubB
結果
SubA11
SubB22
預期
Line11SubA
Line22Subb
我在ubuntu上嘗試了該程序,它產生了您期望的輸出。
您可能遇到的問題是,在forEach的每次迭代中都返回的行變量在開始時有回車符,因此它會覆蓋字符。
我通過在行變量的開頭有意添加回車符來驗證這一點,它開始產生您要獲得的輸出。
'use strict'
const fs = require('fs')
let targetRegex = /Line*/;
let concatStatement = '';
fs.readFileSync('input.txt').toString().split('\n')
.forEach(function (line) {
line = '\r' + line
if (targetRegex.test(line)) {
concatStatement = line;
}
else {
concatStatement += line
console.log(concatStatement);
}
});
這產生
SubA11
SubB22
如果我評論這一行
line = '\r' + line
然后產生(在我的平台上)您期望的輸出。
解
要解決此問題,可以檢查input.txt文件的行分隔符,然后使用正確的分隔符作為文本分隔符。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.