我想在浏览器中解析 grep 命令的结果。
类似于 grep -nriI "hello"myFolder
结果是一个多行字符串:
/home/user/folder/file1:1:hello world /home/user/folder/file2:1:world hello /home/user/folder/folder/file3:1:bonjour=hello
首先,我将行拆分成一个数组。并使用此正则表达式解析它:/^(.*?)\:(\d*)\:(.*?)$/
我有一些问题。
- Parse 不适用于双点 (:) 等有趣字符的结果
- 当我 grep 一个文件时,我没有得到
pah:line number:content
但只有line number:content
所以它使正则表达式更复杂(没有javascript 正则表达式中的命名组)。
有人已经有了一个好的解析器或一个解析它的项目。它必须在浏览器中工作...
我会制作一个 jsfiddle。
最佳答案
我的 grep(在 Ubuntu Linux 上)有一些可能有用的选项,尽管它们都不是 POSIX 标准。
对于不明确的输出:
-Z, --null
Output a zero byte (the ASCII NUL character) instead of the character
that normally follows a file name. For example, grep -lZ outputs a zero
byte after each file name instead of the usual newline. This option
makes the output unambiguous, even in the presence of file names
containing unusual characters like newlines. This option can be used
with commands like find -print0, perl -0, sort -z, and xargs -0 to
process arbitrary file names, even those that contain newline characters.
对于丢失的文件名:
-H, --with-filename
Print the file name for each match. This is the default when there is
more than one file to search.
所以使用 grep -nriIHZ
并将正则表达式更新为如下内容(未经测试):
/^(.*)\0(\d+):(.*)$/
关于javascript - 使用javascript在浏览器中解析grep的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10880640/