Do you know JavaScript and want to write a shell script? Then you should give Node.js a try. It is easy to install and shell scripts are a great way to get to know it. This post explains the basics.
[ nodeBinary, script, arg0, arg1, ... ]Thus, the first argument is at process.argv[2] and you can loop over all arguments via:
process.argv.slice(2).forEach(function (fileName) { ... });If you want to do more sophisticated argument processing, you can take a look at the Node.js modules nomnom and optimist. From now on, we’ll frequently use the file system module:
var fs = require('fs');
var text = fs.readFileSync(fileName, "utf8");Afterwards, you can split the text, to process the content line by line.
text.split(/\r?\n/).forEach(function (line) { // ... });For larger files, you can work with a stream to iterate over the lines. mtomis describes one solution at Stack Overflow.
fs.writeFileSync(fileName, str, 'utf8');Or you can incrementally write strings to a stream.
var out = fs.createWriteStream(fileName, { encoding: "utf8" }); out.write(str); out.end(); // currently the same as destroy() and destroySoon()
var EOL = fileContents.indexOf("\r\n") >= 0 ? "\r\n" : "\n";Solution 2: Check the platform. All Windows platforms return "win32", even 64bit ones.
var EOL = (process.platform === 'win32' ? '\r\n' : '\n')
var path = require('path'); path.join(mydir, "foo");
node myscript.js arg1 arg2 ...On Unix, you have the option to prepend a line telling the operating system how to run the script:
#!/usr/bin/env nodeThen you only need to make the script executable:
chmod u+x myscript.jsNow it can be run on its own:
./myscript.js arg1 arg2 ...