bash Bash脚本如何找到文件夹中的每个文件并在其上运行命令

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19328561/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-10 00:18:38  来源:igfitidea点击:

Bash Script How to find every file in folder and run command on it

bash

提问by user2872510

So im trying to create a script that looks in a folder and finds all the file types that have .cpp and run g++ on them. so far i have but it doesn't run it says unexpected end

因此,我尝试创建一个脚本,该脚本在文件夹中查找并查找所有具有 .cpp 的文件类型并在其上运行 g++。到目前为止我有但它没有运行它说意外结束

for i in `find /home/Phil/Programs/Compile -name *.cpp` ; do echo $i ; 
done

Thanks

谢谢

回答by Gavin Smith

The problem with your code is that the wildcard *is being expanded by the shell before being passed to find. Quote it thusly:

您的代码的问题在于通配符*在传递给 find 之前被 shell 扩展。引用它:

for i in `find /home/Phil/Programs/Compile -name '*.cpp'` ; do echo $i ;  done

xargsas suggested by others is a good solution for this problem, though.

xargs不过,正如其他人所建议的那样,这是一个很好的解决方案。

回答by William Pursell

findhas an option for doing exactly that:

find有一个选项可以做到这一点:

find /p/a/t/h -name '*.cpp' -exec g++ {} \;

回答by EverythingRightPlace

You could use xargs like:

你可以使用 xargs 像:

find folder/ -name "*.cpp" | xargs g++

find folder/ -name "*.cpp" | xargs g++

Or if you want to handle files which contain whitespaces:

或者,如果您想处理包含空格的文件:

find folder/ -name "*.cpp" -print0 | xargs -0 g++

find folder/ -name "*.cpp" -print0 | xargs -0 g++

回答by Bryan Newman

I think you want to use xargs:

我想你想使用xargs

For example:

例如:

find /home/Phil/Programs/Compile -name *.cpp | xargs g++

回答by Blue Ice

This code works for me:

这段代码对我有用:

#!/bin/bash

for i in `find /home/administrator/Desktop/testfolder -name *.cpp` ; do echo $i ; 
done

I get:

我得到:

administrator@Netvista:~$ /home/administrator/Desktop/test.sh
/home/administrator/Desktop/testfolder/main.cpp
/home/administrator/Desktop/testfolder/main2.cpp

回答by suripoori

How about using xargs like this:

像这样使用 xargs 怎么样:

find $working_dir -type f -name *.cpp | xargs -n 1 g++