Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

for loop over specific files in a directory using Bash

Tags:

bash

for-loop

In a directory you have some various files - .txt, .sh and then plan files without a .foo modifier.

If you ls the directory:

blah.txt blah.sh blah blahs 

How do I tell a for-loop to only use files without a .foo modify? So "do stuff" on files blah and blahs in the above example.

The basic syntax is:

#!/bin/bash FILES=/home/shep/Desktop/test/*  for f in $FILES do     XYZ functions done 

As you can see this effectively loops over everything in the directory. How can I exclude the .sh, .txt or any other modifier?

I have been playing with some if statements but I am really curious if I can select for those non modified files.

Also could someone tell me the proper jargon for these plain text files without .txt?

like image 898
jon_shep Avatar asked Feb 12 '13 01:02

jon_shep


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 go to a specific directory in bash?

To change directories, use the command cd followed by the name of the directory (e.g. cd downloads ). Then, you can print your current working directory again to check the new path.


2 Answers

#!/bin/bash FILES=/home/shep/Desktop/test/*  for f in $FILES do if [[ "$f" != *\.* ]] then   DO STUFF fi done 
like image 95
David Kiger Avatar answered Sep 27 '22 17:09

David Kiger


If you want it a little bit more complex, you can use the find-command.

For the current directory:

for i in `find . -type f -regex \.\\/[A-Za-z0-9]*` do WHAT U WANT DONE done 

explanation:

find . -> starts find in the current dir -type f -> find only files -regex -> use a regular expression \.\\/[A-Za-z0-9]* -> thats the expression, this matches all files which starts with ./ (because we start in the current dir all files starts with this) and has only chars and numbers in the filename. 

http://infofreund.de/bash-loop-through-files/

like image 31
chris2k Avatar answered Sep 27 '22 19:09

chris2k