bash 为目录中的每个文件运行 shell 脚本

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10259836/
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-18 02:06:16  来源:igfitidea点击:

Run shell script for every file in directory

linuxbashunixfindxargs

提问by general exception

I have a bunch of files in a directory all named YYYY_MM_DD

我在一个目录中有一堆文件都命名为 YYYY_MM_DD

-rw-r--r-- 1 root root 480K Apr 21 13:17 2012_04_05
-rw-r--r-- 1 root root 483K Apr 21 13:17 2012_04_06
-rw-r--r-- 1 root root 484K Apr 21 13:17 2012_04_07
-rw-r--r-- 1 root root 480K Apr 21 13:17 2012_04_08
-rw-r--r-- 1 root root 344K Apr 21 13:17 2012_04_09
-rw-r--r-- 1 root root  66K Apr 21 13:17 2012_04_10
-rw-r--r-- 1 root root 461K Apr 21 13:17 2012_04_11
-rw-r--r-- 1 root root 475K Apr 21 15:09 2012_04_17
-rw-r--r-- 1 root root 480K Apr 21 15:10 2012_04_18
-rw-r--r-- 1 root root 474K Apr 21 15:10 2012_04_19
-rw-r--r-- 1 root root 474K Apr 21 15:10 2012_04_20

I have a shell script that accepts a file as a paramater and calculates figures based on the data in the file, i call the script like this

我有一个 shell 脚本,它接受一个文件作为参数并根据文件中的数据计算数字,我像这样调用脚本

sh Calculate.sh MyFile

I want to run this shell script for every file in this directory.

我想为这个目录中的每个文件运行这个 shell 脚本。

How would i go about doing this, xargs ??

我将如何去做,xargs ?

采纳答案by MrJames

Have you tried the findcommand with execution ?

您是否尝试过find执行命令?

My sample will echo the files, but you can call a shell script with the filename as a parameter

我的示例将回显文件,但您可以使用文件名作为参数调用 shell 脚本

find . -maxdepth 1 -type f -exec echo {} \;

回答by glenn Hymanman

A simple for loop in the shell:

shell 中的一个简单的 for 循环:

for file in *; do sh Calculate.sh "$file"; done

回答by user unknown

./Calculate.sh 2012_04_{05..20}

回答by Dagang

find . -maxdepth 1 -type f | xargs -n 1 -I % Calculate.sh %

find . -maxdepth 1 -type f | xargs -n 1 -I % Calculate.sh %