英文:
Copy files containing one of the word from list
问题
我有一个庞大的代码库在我面前。在这个代码库中,我想要找到包含类定义的文件(路径),然后将这些文件复制到一个文件夹中。我有一个包含大约50个类名的列表要查找。
我尝试过使用grep
,像这样:
cp $(grep --include=*.java -rl . -e "class SplashScreen" *) --parents -t ./dest-folder
这个方法可以工作,但要花费很长时间来查找一个类。
我可以编写一个循环脚本来查找每个类名,但这将需要很长时间,而且我不想为每个类手动执行这个操作。
有没有更好的方法来做这件事?
英文:
I have large code base in front of me. In this I want to find the files(path) that contain the class definition and copy the file to a folder. I have a list of class names(about 50) to look for.
I've tried using grep
like
cp $(grep --include=\*.java -rl . -e "class SplashScreen" *) --parents -t ./dest-folder
It works, but it takes a lot of time to find even one class through code.
I could write a script looping though every class name will take a long time and i don't want to do it manually for every class.
Is there a better way to do this?
答案1
得分: 1
假设您有一个包含类名的文件`list.txt`(每行一个类名):
MyClass1
MyClass2
MyInterface1
可以处理此文件以构建一个正则表达式来选择类名并将其存储到变量中:
$ class_names="$(cat list.txt|tr '\n' '#'|sed 's/#/\|/g')"
然后,您可以使用`grep`运行脚本,或者您可以使用`find`。
$ cp $(find ./src -type f -name "*.java" -exec grep -l "(class|interface) ($class_names)" {} +) --parents -t ./mydest-dir
或者,没有临时变量,最终命令可能如下所示:
$ cp $(find ./src -type f -name "*.java" -exec grep -l "(class|interface) ($(cat list.txt|tr '\n' '#'|sed 's/#/\|/g'))" {} +) --parents -t ./mydest-dir
为了确保所需文件成功复制,使用相同的`find`:
$ find ./mydest-dir -type f -name "*.java"
英文:
Assuming that you have a list of class names in a file list.txt
(one class name per line):
MyClass1
MyClass2
MyInterface1
it is possible to process this file to build up a regexp to select the class names and store it into a variable:
$ class_names="$(cat list.txt|tr '\n' '#'|sed 's/#/\\|/g')"
Then you can run your script using grep
or you could use find
.
$ cp $(find ./src -type f -name "*.java" -exec grep -l "\(class\|interface\) \($class_names\)" {} +) --parents -t ./mydest-dir
Or, without the temporary variable the final command may look like this:
$ cp $(find ./src -type f -name "*.java" -exec grep -l "\(class\|interface\) \($(cat list.txt|tr '\n' '#'|sed 's/#/\\|/g')\)" {} +) --parents -t ./mydest-dir
To make sure the required files are copied successfully, use the same find
:
$ find ./mydest-dir -type f -name "*.java"
答案2
得分: 0
使用 -f
来定义一个要应用的模式文件。你可以在这些模式中包含正则表达式元字符。
你可以使用 shopt -s globstar
来访问不确定深度的文件名。
如果 pats
是你的模式文件的名称,
shopt -s globstar
cp --parents -t ./dest-folder $( grep -l -f pats **/*.java )
英文:
Use -f
to define a file of patterns to apply. You can include regex metacharacters in the patterns.
You can use shopt -s globstar
to access filenames at indeterminate depth.
If pats
is the name of your pattern file,
shopt -s globstar
cp --parents -t ./dest-folder $( grep -l -f pats **/*.java )
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论