Skip to content

Instantly share code, notes, and snippets.

@zeuxisoo
Last active September 8, 2021 06:32
Show Gist options
  • Save zeuxisoo/6239784 to your computer and use it in GitHub Desktop.
Save zeuxisoo/6239784 to your computer and use it in GitHub Desktop.
Using the node.js or sed command to replace the text in yo.txt file

Structure

foo
    data
        yo1.csv
        yo2.csv
    Makefile
    yo1.js
    yo2.js
run:
sed 's/"\([[:alnum:]]*\),\([[:alnum:]]*\)"/"\1:\2"/g' data/yo.csv > data/yo.sed.csv
test:
@echo "a,b,c,d,e,\"a,b\",f,g,\"h,i\",j,k\n1,2,3,4,5,\"6,7\",8,9,\"10,11\",12,13" | \
sed 's/"\([[:alnum:]]*\),\([[:alnum:]]*\)"/"\1:\2"/g'
a b c d e a,b f g h,i j k
1 2 3 4 5 6,7 8 9 10,11 12 13
#!/usr/bin/env node
var fs = require('fs');
fs.readFile('data/yo1.csv', function(err, data) {
data.toString().split("\r\n").forEach(function(line) {
line = line.replace(/"([A-Za-z0-9]+),([A-Za-z0-9]+)"/g, '"$1:$2"');
console.log(line);
});
});
1 2 3,4 5 6 7,8,9 10 11,12,13,14
a b c,d e f g,h,i j k,l,m,n
#!/usr/bin/env node
var fs = require('fs');
fs.readFile('data/yo2.txt', function(err, data) {
data.toString().trim().split("\n").forEach(function(line) {
var matches = line.match(/"(.*?)"/g);
for(var i=0, l=matches.length; i<l; i++) {
line = line.replace(matches[i], matches[i].replace(/,/g, ":"));
}
console.log(line);
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment