简体   繁体   English

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

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

Scenario : 场景:

A folder in Linux system. Linux系统中的一个文件夹。 I want to loop through every .xls file in a folder. 我想遍历文件夹中的每个.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. 问题是我必须执行的程序是'xls2csv'才能从.xls转换为.csv格式。 So, for each .xls file I have to grab the filename and append it to .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? 我有道理吗?

庆典:

for f in *.xls ; do xls2csv "$f" "${f%.xls}.csv" ; done
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 . do的第一行检查“匹配”文件是否确实存在,因为如果你的for没有匹配,则do将以“* .xls”作为$i This could be horrible for your xls2csv . 这对你的xls2csv可能很糟糕。

Look at the find command. 查看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. 更接近你想要的。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM