如何使用grep获得唯一结果?

3
以下场景是我想要作为Jenkins工作的一部分实现逻辑的一部分。我正在尝试编写一个shell脚本。
我使用grep命令来递归搜索一个特定字符串。grep返回的样本结果如下所示:
./src/test/java/com/ABC/st/test/pricing/Test1.java: @Tags({ "B-05256" }) ./src/test/java/com/ABC/st/test/pricing/Test1.java: @MapToVO(storyID = "B-05256: prices in ST") ./src/test/java/com/ABC/st/test/pricing/Test1.java: @Tags({ "B-05256" }) ./src/test/java/com/ABC/st/test/pricing/Test2.java: @Tags({ "B-05256" }) ./src/test/java/com/ABC/st/test/pricing/Test2.java: @MapToVO(storyID = "B-05256:Lowest Price of the Season") ./src/test/java/com/ABC/st/test/pricing/Test2.java: @Tags({ "B-05256" })
我想提取唯一的文件路径,例如:
/src/test/java/com/ABC/st/test/pricing/Test1.java
/src/test/java/com/ABC/st/test/pricing/Test2.java

然后在Maven命令中使用每个唯一的路径。因此:

  1. 如何从grep命令给出的结果集中提取唯一的文件路径?

  2. 如何运行一个类似循环的东西,在每次迭代中使用唯一的文件路径执行mvn命令?


感谢大家的建议。我已经使用以下命令提取所有唯一的文件路径:find . -type f -name "*.java" -exec grep -il 'stella-env-upgrade' {} ; 现在我想在每个文件路径上执行一个Maven命令。我该怎么做? - silver_noodles
选择这里的一个答案作为正确答案,如果您还需要更多帮助,请提出一个跟进问题。但是回答您的问题很可能涉及使用 xargs。另外,您可以只使用 -r--include 标志来使用 grep,而不需要涉及 find - Etan Reisner
3个回答

3
如果您只需要匹配文件的名称,可以使用grep命令行开关来实现:
-l, --files-with-matches
       Suppress  normal  output; instead print the name of each input file from which output
       would normally have been printed.  The scanning will stop on the first match.  (-l is
       specified by POSIX.)

谢谢。现在我该如何在那个文件名上执行命令呢?例如,我该如何将该文件名传递给Maven命令。我对Shell脚本非常陌生。 - silver_noodles

1
将您的文本导入管道中。
sed 's/:.*//' | sort -u | while read path
do
    echo now execute your command using "$path"
done

0
这就是grep命令中-l标志的作用。

-l, --files-with-matches

抑制正常输出,而是打印出通常会打印输出的每个输入文件的名称。扫描将在第一个匹配项处停止。(-l由POSIX指定。)


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接