• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 341
  • Last Modified:

Bash regex to match files that end with specific extensions

I'm trying to iterate over the files in a directory and perform an operation on only the files with specific extensions. Unfortunately my bash-fu is weak today, can anyone help?

In this example, I'm looking for files that end with ".txt" or ".doc":

for myFile in $myDir
do
   if [[ $myFile =~ \.(txt|doc)$ ]] ; then
      echo $myFile 
   fi
done

Open in new window

0
Mark Olsen
Asked:
Mark Olsen
  • 2
  • 2
  • 2
  • +1
1 Solution
 
woolmilkporcCommented:
Why not use "find"

find $myDir -type f \( -name "*.txt" -o -name "*.doc" \)

If you don't want to recurse into subdirectories add "-maxdepth 1"

find $myDir -maxdepth 1 -type f \( -name "*.txt" -o -name "*.doc" \)
0
 
woolmilkporcCommented:
Or extended globbing?

shopt -s extglob
for myFile in $myDir/+(*.docx|*.txtx)
do
     echo $myFile
done

or short:

shopt -s extglob
ls -1 $myDir/+(*.docx|*.txtx)
0
 
Mark OlsenSr. DeveloperAuthor Commented:
Using "find" did the trick. Thank you for the fast answer. Like I said, my bash-fu is weak today and I forgot about that command.
0
Free Tool: Subnet Calculator

The subnet calculator helps you design networks by taking an IP address and network mask and returning information such as network, broadcast address, and host range.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

 
tel2Commented:
I guess this is a bit late now...

#!/bin/bash

myDir=dir1

for myFile in `find $myDir -regextype posix-awk -regex '.*(txt|doc)'`
do
        echo $myFile
done

Open in new window


This gives entire file paths.  Not sure if that's what you wanted.
0
 
TintinCommented:
or simply

cd $myDir

for myFile in *.txt *.doc
do 
      echo $myFile 
done

Open in new window

0
 
tel2Commented:
Well said, Tintin.

Would that run into problems if there were too many matching files?
0
 
TintinCommented:
Would that run into problems if there were too many matching files?

Indeed it will.   In most cases, the globbing limits aren't an issue.   Depends on the nature of the task.
0

Featured Post

Upgrade your Question Security!

Your question, your audience. Choose who sees your identity—and your question—with question security.

  • 2
  • 2
  • 2
  • +1
Tackle projects and never again get stuck behind a technical roadblock.
Join Now