Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

linux

shell

Scenario :

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

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

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

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.

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

Did I make sense?

like image 765
ThinkCode Avatar asked Feb 19 '10 15:02

ThinkCode


People also ask

How can I iterate over files in a given directory bash?

The syntax to loop through each file individually in a loop is: create a variable (f for file, for example). Then define the data set you want the variable to cycle through. In this case, cycle through all files in the current directory using the * wildcard character (the * wildcard matches everything).

How do I iterate through a directory in Linux?

To loop through a directory, and then print the name of the file, execute the following command: for FILE in *; do echo $FILE; done.


2 Answers

bash:

for f in *.xls ; do xls2csv "$f" "${f%.xls}.csv" ; done 
like image 198
Ignacio Vazquez-Abrams Avatar answered Sep 20 '22 19:09

Ignacio Vazquez-Abrams


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.

like image 37
AndrewBourgeois Avatar answered Sep 21 '22 19:09

AndrewBourgeois