在nodejs行号处插入字符串

问题描述 投票:0回答:3

我有一个文件想要修改。有没有办法将字符串插入到文件的特定行号处?与 NodeJS

真的很感谢你对我的帮助

javascript node.js file
3个回答
39
投票

只要文本文件不是那么大,您应该能够将文本文件读入数组,将元素插入到特定的行索引中,然后将数组输出回文件。我在下面放置了一些示例代码 - 确保更改

'file.txt'
"Your String"
和特定的
lineNumber

免责声明,我还没有时间测试以下代码:

var fs = require('fs');

var data = fs.readFileSync('file.txt').toString().split("\n");
data.splice(lineNumber, 0, "Your String");
var text = data.join("\n");

fs.writeFile('file.txt', text, function (err) {
  if (err) return console.log(err);
});

0
投票

@VineetKosaraju 代码的更简单版本是:

let yaml_str = `---
up:
tags:
related: candidate
uuid: "20240215"
---
`

const lineNumber = 1                             // at the top
var txt = yaml_str.toString().split("\n");
txt.splice(lineNumber, 0, "location: 'Houston'");
txt = txt.join("\n");

console.log(txt)

我在 Obsidian.md 中使用这个。

输出为:

---
location: 'Houston'
up:
tags:
related: candidate
uuid: "20240215"
---

-2
投票

如果您使用的是 Unix 系统,那么您可能需要使用

sed
,就像这样在文件中间添加一些文本:

#!/bin/sh
text="Text to add"
file=data.txt

lines=`wc -l $file | awk '{print $1}'`

middle=`expr $lines / 2`

# If the file has an odd number of lines this script adds the text
# after the middle line. Comment this block out to add before
if [ `expr $lines % 2` -eq 1 ]
then
  middle=`expr $middle + 1`
fi

sed -e "${middle}a $text" $file

注意:上面的例子来自这里

使用 NodeJS 似乎有一些 npm 软件包可能会有所帮助,例如 sed.jsreplace

© www.soinside.com 2019 - 2024. All rights reserved.