簡體   English   中英

如何刪除換行符並制作單行文本?

[英]How to remove line breaks and make single line text?

我有一個日志文件,其中事件多行顯示。 為了使事件成為一行,首先我必須將包含日期的行和沒有日期的行分開。 現在,我試圖編寫一種邏輯來檢查一行,如果它沒有日期,請將其與prevLine合並。

如何使用正則表達式或其他有助於完成此任務的模塊將多行合並為一個?

ctrl.js

var regex = /\[\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\w+\]/;
var prevLine;
var readStream = fs.createReadStream(dir + '/' + logFile,'utf8');
        readStream.pipe(split()).on('data', function (line) {
            if (regex.test(line)) {
                    console.log('Line with date:', line);
                    parseLog(line,prevLine);
                } else {
                    console.log('Line without date:', line);
                    line = prevLine + line;
                }
                function parseLog(line, prev) {
                    if (line.indexOf('|') === -1) line = prev + line;
                 }
          });

fileData

[2017-03-23T18:13:16Z]|verbose|bmid: n/a|infra.topicWorkers|topology changed, emitting topology event { newTopology: 
   [ '-0000001337',
     '-0000001338',
     '-0000001339',
     '-0000001340',
     '-0000001341',
     '-0000001342' ],
  oldTopology: 
   [ '-0000001337',
     '-0000001338',
     '-0000001339',
     '-0000001340',
     '-0000001341' ],
  workerId: 6,
  pid: 30488 }
[2017-03-23T18:13:16Z]|verbose|bmid: n/a|infra.topicWorkers|topology changed, emitting topology event { newTopology: 
   [ '-0000001337',
     '-0000001338',
     '-0000001339',
     '-0000001340',
     '-0000001341',
     '-0000001342' ],
  oldTopology: [],
  workerId: 4,
  pid: 30481 }

您可以執行以下操作:

const split = require('split');
const regex = /\[\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\w+\]/;
let items = [];
let item = [];
fs.createReadtStream(path.join(dir, logFile), 'utf8')
  .pipe(split()).on('data', (line) => {
    if (regex.test(line)) {
        item = [];
        items.push(item);
    }
    item.push(line);
});
let lines = items.map(item => item.join(' '));
lines.forEach(line => console.log(line));

您可以在每次有新行時向數組添加新行,但是當有日期的行時,可以將該數組放入另一個數組並為這些單行創建新數組。 然后,您可以通過將內部數組內的元素連接起來來組合它們,您將擁有一個很大的組合線數組-該示例中的數組稱為lines

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM