在目录树中检测无效的 JSON 文件

Dre*_*kes 5 command-line xargs json ubuntu

如果目录树包含一个根据jsonlintNPM 包无效的 JSON 文件,我想使构建失败。

我认为这就像运行一样简单:

find . -name \*.json | xargs jsonlint -q
Run Code Online (Sandbox Code Playgroud)

我知道我在磁盘上有一个格式错误的 JSON 文档,但这并没有找到它。

进一步调查显示该find命令按预期工作,但是该jsonlint可执行文件仅被调用一次(并且第一个 JSON 文件是正确的。)

有没有更好的方法来做到这一点,或者我需要在xargs这里学习什么?

我正在运行 Ubuntu 13.10 Server,如果需要,可以安装软件包。

ter*_*don 8

看起来jsonlint无法处理多个文件:

$ jsonlint -h

Usage: jsonlint [file] [options]

file     file to parse; otherwise uses stdin
Run Code Online (Sandbox Code Playgroud)

请注意,它总是说file,而不是files。当您运行命令并将其输出通过管道传输到xargs您所做的工作时,xargs将简单地连接命令的所有输出并将其作为输入传递给您告诉它执行的任何内容。例如:

$ printf "foo\nbar\nbaz\n"
foo
bar
baz
$ printf "foo\nbar\nbaz\n" | xargs echo
foo bar baz
Run Code Online (Sandbox Code Playgroud)

这表明您执行的命令xargs

echo foo bar baz
Run Code Online (Sandbox Code Playgroud)

在这种情况下jsonlint,您想要做的不是jsonlint -q foo bar baz但是

$ jsonlint -q foo
$ jsonlint -q bar
$ jsonlint -q baz
Run Code Online (Sandbox Code Playgroud)

最简单的方法是find按照@fede.evol 的建议使用:

$ find . -name \*.json -exec xargs jsonlint -q {} \;
Run Code Online (Sandbox Code Playgroud)

要做到这一点,xargs您需要使用-I标志:

   -I replace-str
          Replace occurrences of replace-str in the initial-arguments with
          names read from standard input.  Also, unquoted  blanks  do  not
          terminate  input  items;  instead  the  separator is the newline
          character.  Implies -x and -L 1.
Run Code Online (Sandbox Code Playgroud)

例如:

$ find . -name \*.json  | xargs -I {} jsonlint -q {}
Run Code Online (Sandbox Code Playgroud)

或者,要安全地处理奇怪的名称(例如包含换行符):

$ find . -name \*.json -print0  | xargs -0I {} jsonlint -q '{}'
Run Code Online (Sandbox Code Playgroud)