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

时间:2021-12-21 17:31:13

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 root and 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

例如,我有一个测试。xls文件和xls2csv的参数为:xls2csv测试。xls test.csv

Did I make sense?

我的存在有意义吗?

4 个解决方案

#1


159  

bash:

bash:

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

#2


11  

Look at the find command.

查看查找命令。

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文件。xls file.xls.csv

Closer to what you want.

更接近你想要的。

#3


10  

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

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

如果“匹配”文件确实存在,那么在do检查的第一行中,因为在您的for中没有任何匹配项时,do将与“*”一起执行。xls”我美元。这对xls2csv来说可能很糟糕。

#4


2  

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

#1


159  

bash:

bash:

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

#2


11  

Look at the find command.

查看查找命令。

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文件。xls file.xls.csv

Closer to what you want.

更接近你想要的。

#3


10  

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

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

如果“匹配”文件确实存在,那么在do检查的第一行中,因为在您的for中没有任何匹配项时,do将与“*”一起执行。xls”我美元。这对xls2csv来说可能很糟糕。

#4


2  

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