0

I have a file which consists of places where there are multiple underscores. I need to convert them all to single underscores.

How can I do this in Node?

My current solution:

var fs = require("fs");
filename = "questions.txt";
ofilename = "o.txt";
fs.readFile(filename, "utf8", function (err, data) {
  if (err) {
    return console.log(err);
  }
  var result = data.replace(/_+/g, "_");

  fs.writeFile(ofilename, result, "utf8", function (err) {
    if (err) return console.log(err);
  });
});

This gives me a file where everything is in binary.

5
  • You can do this without JS, using sed in terminal sed 's/__*/_/g' questions.txt Commented Jul 22, 2020 at 13:42
  • the data remains the same Commented Jul 22, 2020 at 13:55
  • add > o.txt to save to a file sed 's/__*/_/g' test.txt > o.txt Commented Jul 22, 2020 at 13:58
  • or -i to modify file sed -i 's/__*/_/g' test.txt Commented Jul 22, 2020 at 13:59
  • @JacekRojek sorry it might have been an encoding issue. this gave me the same result on utf16. but on changing to utf8 everything works. Commented Jul 22, 2020 at 14:01

1 Answer 1

1

Your code works well.

var fs = require("fs");
filename = "./questions.txt";
ofilename = "o.txt";
fs.readFile(filename, "utf8", function (err, data) {
  if (err) {
    return console.log(err);
  }
  console.log(data);
  var result = data.replace(/_+/g, "_");

  fs.writeFile(ofilename, result, "utf8", function (err) {
    if (err) return console.log(err);
  });
});
  • produces:
toto

_
_
rr
  • from:
toto

__
__
rr

Be sure that your input file is well utf8 encoded.

Sign up to request clarification or add additional context in comments.

5 Comments

ibb.co/yNcyP53 the output is this, when I run it
I am not sure if my input file is utf8. It is just a txt file. What other formats can I use?
and show your input file encoding (at bottom right of the ide)
it says utf16le
So click on it, select "save with encoding" and select "utf8", assuming you are on vscode

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.