grep正则匹配

grep正则匹配

grep -E命令支持高级正则匹配,egrep是它的快捷方式

实例:

查找nodejs项目下所有router注册地址,并保存到doc.txt文件

1
egrep -ir 'router\.(get|post)' ./routes > doc.txt

output:

1
2
3
4
./routes/records.js:router.post('/switch/get', async function(req, res, next){
./routes/records.js:router.post('/switch/set', async function(req, res, next){
./routes/records.js:router.post('/dict/get', async function(req, res, next){
...

通过nodejs将以上内容抽取出来并进行格式化成markdowntable, 并预留description

test.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
const fs = require('fs');
const { readFileSync, writeFileSync } = fs;
const docs = readFileSync('./doc.txt');
const list = docs.toString().split('\n');

const markdown = [];
const titles = ['file', 'method', 'uri', 'description'];

markdown.push(`|${titles.join('|')}|`);
markdown.push(`|${'---|'.repeat(titles.length)}`);

list
.filter(x => x)
.forEach(x => {
const [path, source] = x.split(':');
const matchpath = path.match(/\/(?<filename>[^\/]*?\.js)/);
const { filename } = matchpath.groups;

const matchsource = source.match(/(?<method>get|post)\('(?<uri>[^']*)/);
const { uri, method } = matchsource.groups;

if (uri !== '/') {
const data = [filename, method, uri, ''];
markdown.push(`|${data.join('|')}|`);
}
});

writeFileSync('./doc.md', markdown.join('\n'));

运行node test.js则会生成doc.md

nodejs处理文件还是挺方便的。 熟练运用的话,以上文件只花两分钟就能搞定

#

Comments

Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×