jon_shep
jon_shep

Reputation: 1463

for loop over specific files in a directory using Bash

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?

Upvotes: 34

Views: 86691

Answers (3)

chris2k
chris2k

Reputation: 169

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/

Upvotes: 14

David Kiger
David Kiger

Reputation: 1996

#!/bin/bash
FILES=/home/shep/Desktop/test/*

for f in $FILES
do
if [[ "$f" != *\.* ]]
then
  DO STUFF
fi
done

Upvotes: 44

Blender
Blender

Reputation: 298136

You can use negative wildcards? to filter them out:

$ ls -1
a.txt
b.txt
c.png
d.py
$ ls -1 !(*.txt)
c.png
d.py
$ ls -1 !(*.txt|*.py)
c.png

Upvotes: 3

Related Questions