目录中每个文件的 Linux Shell 脚本获取文件名并执行程序

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

Linux Shell Script For Each File in a Directory Grab the filename and execute a program

linuxshell

提问by ThinkCode

Scenario :

设想 :

A folder in Linux system. I want to loop through every .xls file in a folder.

Linux系统中的一个文件夹。我想遍历文件夹中的每个 .xls 文件。

This folder typically consists of various folders, various filetypes (.sh, .pl,.csv,...).

该文件夹通常由各种文件夹、各种文件类型(.sh、.pl、.csv 等)组成。

All I want to do is loop through all files in the rootand execute a program only on .xls files.

我想要做的就是遍历根目录中的所有文件并仅在 .xls 文件上执行程序。

Edit :

编辑 :

The problem is the program I have to execute is 'xls2csv' to convert from .xls to .csv format. So, for each .xls file I have to grab the filename and append it to .csv.

问题是我必须执行的程序是“xls2csv”以将 .xls 格式转换为 .csv 格式。因此,对于每个 .xls 文件,我必须获取文件名并将其附加到 .csv。

For instance, I have a test.xls file and the arguments fro xls2csv are : xls2csv test.xls test.csv

例如,我有一个 test.xls 文件,xls2csv 的参数是: xls2csv test.xls test.csv

Did I make sense?

我说的有道理吗?

采纳答案by Ignacio Vazquez-Abrams

bash:

重击:

for f in *.xls ; do xls2csv "$f" "${f%.xls}.csv" ; done

回答by Tom

Look at the findcommand.

查看find命令。

What you are looking for is something like

你正在寻找的是类似的东西

find . -name "*.xls" -type f -exec program 

Post edit

发表编辑

find . -name "*.xls" -type f -exec xls2csv '{}' '{}'.csv;

will execute xls2csv file.xls file.xls.csv

将执行 xls2csv file.xls file.xls.csv

Closer to what you want.

更接近你想要的。

回答by ghostdog74

find . -type f -name "*.xls" -printf "xls2csv %p %p.csv\n" | bash

bash 4 (recursive)

bash 4(递归)

shopt -s globstar
for xls in /path/**/*.xls
do
  xls2csv "$xls" "${xls%.xls}.csv"
done

回答by AndrewBourgeois

for i in *.xls ; do 
  [[ -f "$i" ]] || continue
  xls2csv "$i" "${i%.xls}.csv"
done

The first line in the dochecks if the "matching" file really exists, because in case nothing matches in your for, the dowill be executed with "*.xls" as $i. This could be horrible for your xls2csv.

在第一行do,如果“匹配”文件确实存在,因为在你的情况没有什么比赛的检查for中,do将用“的* .xls”的执行$i。这对您的xls2csv.