再见 gawk / perl / bash, Node.js 在 Unix shell scripting 的新生 — Say goodbye to gawk/perl/bash, greeting to Node.js for Unix shell scripting

20151009 笔记
Posted on Oct. 9, 2015

是的,我们充满痛苦,因为 Mac 没有 gawk。
Yes, we are so painful due to absence of gawk in Mac

有一天,我们要做一件事情,就是要使用 Bash 来解析一个 JSON 文件,提取其中的一个数组,对数组的元素一一进行操作。例如:
One day, we would like to do a simple thing — parsing JSON file and performing some shell command against an array of items out of the JSON. Say,

我有一个 package.json,
I have a package.json

Screen Shot 2015-10-09 at 12.17.30 PM

我要 echo 出每一个人的名字,只要名字,不要班级和版本。
I wanna `echo` all of the plugins names of the dependencies only, without “classes” and “versions”.

于是我想到使用 xargs 配合 gawk 的 gensub 来实现正则分组。但是我失败了,因为我们团队的所有电脑是 Mac,我们不能逼人安装 gawk.
After some Googling, I pick `gawk` tool, working in concert with `xargs` via `gensub`. Ooooops, I was blamed by other teammates after git push, since no one has installed `gawk` via Homebrew in their Mac. 

等等,要不使用 perl? 就是这个
Wait , why not do some tricks with `perl` as suggested

Screen Shot 2015-10-09 at 12.21.12 PM

 

可是我们是一群 JS 全栈工程师,并没有几个人会 perl。
Too bad, we are a JS fullstack team, lacking understanding with `Perl`.

于是,我们灵机一动,为什么不使用 node 来取代 perl 呢?
Now what? There is some light shedding out from Paul Lan’s brain. Why not `Node` with –eval switch?

所以结果是:
Ahah…. here it is:

Screen Shot 2015-10-09 at 12.48.21 PM

Screen Shot 2015-10-09 at 12.49.19 PM

看到了么?所有的核心字处理的地方都由 node 完成,结果使用 xargs 重定向给命令 —— 这里以 echo 为例子, {} 为 xargs 修饰符。
See? All major String hard work is done by Javascript through Node, with result redirection to `xargs` and echo. 

Happy
喜乐

守望小方
Paul Lan

Leave a Reply

Your email address will not be published. Required fields are marked *