ITlover00 2019-11-03
今天调试环境上遇到一个问题,我需要查询一个接口是在哪个微服务里面定义的。于是我使用find ./ -name 'interface.json' | grep /user/login
查找接口的位置,每个微服务的接口都定义在一个叫做interface.json的文件里面。
查找结果为空,分析原因如下:
find ./ -name 'interface.json'
查找出来的内容是所有名为interface.json的文件的相对路径,文件路径是不包含接口信息的。grep [OPTIONS] PATTERN [FILE...]
,如果filename为空,则会从标准输入中进行匹配。执行了find ./ -name 'interface.json'
命令之后就会将结果保存到标准输入中。 综合以上两点,我们可以确定grep
命令只是在find ./ -name 'interface.json'
的结果中查找接口信息,所以结果为空。
那么我们需要的结果应该怎么查出来呢?我们需要做的是就是将find
命令查找出来的结果作为grep
的参数,让grep命令去文件当中进行匹配。
这是就需要使用xargs
命令了,这个命令之前就看过,但是没有遇到具体的应用场景,根本不知道它什么情况下会使用。xargs的用法如下:xargs [command [initial-arguments]]
命令的作用是将从标准输入读取的数据作为命令的参数作为后面命令的参数,标准输入中的参数以空白符或者换行符分隔。本质上是把读取的参数放在initial-arguments后面,然后执行后面的命令。如果从标准输入中读取的参数项很多,那xargs会多次执行。
综上,我们要从微服务下面的interface.json中找到查找的结果,那么我们就可以使用find ./ -name 'interface.json' | xargs grep /user/login
进行查找。
如果上面的讲述你认为还不够清晰,可以在linux命令行执行man xargs
,也可以直接查看下面贴出来的对命令的描述。
NAME xargs - build and execute command lines from standard input SYNOPSIS xargs [-0prtx] [-E eof-str] [-e[eof-str]] [--eof[=eof-str]] [--null] [-d delimiter] [--delimiter delimiter] [-I replace-str] [-i[replace-str]] [--replace[=replace-str]] [-l[max-lines]] [-L max-lines] [--maxlines[=max-lines]] [-n max-args] [--max-args=max-args] [-s max-chars] [--max-chars=max-chars] [-P max-procs] [--max-procs=max-procs] [--process-slot-var=name] [--interactive] [--verbose] [--exit] [--no-run-if-empty] [--arg-file=file] [--show-limits] [--version] [--help] [command [initial-arguments]] DESCRIPTION This manual page documents the GNU version of xargs. xargs reads items from the standard input, delimited by blanks (which can be protected with double or single quotes or a backslash) or newlines, and executes the command (default is /bin/echo) one or more times with any initial-arguments followed by items read from standard input. Blank lines on the standard input are ignored. The command line for command is built up until it reaches a system-defined limit (unless the -n and -L options are used). The specified command will be invoked as many times as necessary to use up the list of input items. In general, there will be many fewer invocations of command than there were items in the input. This will normally have significant performance benefits. Some commands can usefully be executed in parallel too; see the -P option. Because Unix filenames can contain blanks and newlines, this default behaviour is often problematic; filenames containing blanks and/or newlines are incorrectly processed by xargs. In these situations it is better to use the -0 option, which prevents such problems. When using this option you will need to ensure that the program which produces the input for xargs also uses a null character as a separator. If that program is GNU find for example, the -print0 option does this for you. If any invocation of the command exits with a status of 255, xargs will stop immediately without reading any further input. An error message is issued on stderr when this happens.