笔记:

笔记:

我想找到所有包含关键字File.createTempFile和行号的Java文件。这就是我所做的:

$ find . -name "*.java" | xargs grep -n "File.createTempFile"
./nuxeo-studio-test/src/test/java/com/nuxeo/studio/web/StudioServletTest.java:162:            File tmpFile = File.createTempFile(jarEntryName, null, Environment.getDefault().getTemp());
./nuxeo-studio-ui/src/main/java/com/nuxeo/studio/core/builders/WorkflowFeatureBuilder.java:421:            tmp = File.createTempFile(".workflow-to-zip", ".tmp", workspace.getRoot());
./nuxeo-studio-ui/src/test/java/com/nuxeo/studio/core/backup/TestS3Backup.java:101:        File tempFile = File.createTempFile(RandomStringUtils.randomAlphabetic(5), ".tmp");
./nuxeo-studio-ui/target/classes/com/nuxeo/studio/core/builders/WorkflowFeatureBuilder.java:421:            tmp = File.createTempFile(".workflow-to-zip", ".tmp", workspace.getRoot());
./nuxeo-studio-web/src/main/java/com/nuxeo/studio/web/v1/ProjectResource.java:191:            File zip = File.createTempFile(filename + "-", ".zip", tempRepo);

但是,我发现这个结果太长,无法阅读。我想只保留文件路径和行号。这是预期结果:

./nuxeo-studio-test/src/test/java/com/nuxeo/studio/web/StudioServletTest.java:162
./nuxeo-studio-ui/src/main/java/com/nuxeo/studio/core/builders/WorkflowFeatureBuilder.java:421
./nuxeo-studio-ui/src/test/java/com/nuxeo/studio/core/backup/TestS3Backup.java:101
./nuxeo-studio-ui/target/classes/com/nuxeo/studio/core/builders/WorkflowFeatureBuilder.java:421
./nuxeo-studio-web/src/main/java/com/nuxeo/studio/web/v1/ProjectResource.java:191

有人可以教我怎么做吗?

答案1

有了pcregrep,你可以这样做:

pcregrep --include='\.java$' -rHno1 '()File\.createTempFile' .

输出将如下所示:

./path/to/file.java:12:

如果模式在一行中出现多次,则输出的行数也会相同。如果您不想这样,可以将其更改为:

pcregrep --include='\.java$' -rHno1 '^().*?File\.createTempFile' .

答案2

这是一种方法awk

find . -name '*.java' -exec awk '/PATTERN/{print FILENAME,FNR}' {} +

或者,如果您想模拟grep的输出:

find . -name '*.java' -exec awk '/PATTERN/{printf("%s:%s\n", FILENAME, FNR)}' {} +

答案3

keyW='File.createTempFile'
find . -type f -name '*.java' -exec perl -slne '
  print "$ARGV:$." if /\Q$k\E/; $. = 0 if eof;
' -- -k="$keyW" -- {} +

答案4

esport keyW='File.createTempFile'
find . -name '*.java' -type f -exec sh -c '
   grep -hn "$keyW" "$1" | cut -d":" -f1 |
   while IFS=: read -r n x; do
      printf "%s:%s\n" "$1" "$n"
   done
' {} {} \;

笔记:

grep必须运行 1/每个文件是此方法的限制。

相关内容