1

I want to iterate all the files in a directory in a bash script.

  1. List all files with extentions .LOG .txt .MAP .TL9*
  2. List all files which have no extention.

I am trying this :

for file in *.{LOG,txt,MAP,TL9*}; do

I want to list the files, that only ends with above extension. So, I do not want to list a file: temp.txt.EXT because it does not end with above given extentions. Similarly I don't want this to be reported temp.TL94.JPG or temp.TL9.JPG.

But in this above for loop, how do i insert the check which gives me the file with no extention?

Please help.

Puneet Jain
  • 97
  • 1
  • 10

3 Answers3

1

Using extglob, you can do this:

shopt -s nullglob
shopt -s extglob

for file in @(!(*.*)|*.@(csv|LOG|TL9!(*.*))); do
   echo "$file"
done
anubhava
  • 761,203
  • 64
  • 569
  • 643
  • Yes... but I am using this *.@(LOG|txt|MAP|TL9) !(*.*) – Puneet Jain Oct 05 '16 at 23:50
  • It is exact same glob expression as mine (which I posted earlier) but broken down into 2 separate globs. – anubhava Oct 06 '16 at 06:54
  • Its showing me files like Name.LOG.TMP (because I think it has .LOG in the middle). But i don't this file. I want all the files "ending" with LOG|txt|MAP|TL9* only @anubhava – Puneet Jain Oct 07 '16 at 19:46
  • That's not correct. It won't list `Name.LOG.TMP`. It will only list files ending with `.LOG` – anubhava Oct 07 '16 at 20:25
  • My bad. I gave wrong file name. It was showing me this file Name.TL98.JPG even though i don't want it as it DOES NOT end with .TL9* @anubhava – Puneet Jain Oct 07 '16 at 20:31
1

With extglob:

*.@(LOG|txt|MAP|TL9) !(*.*)
  • *.@(LOG|txt|MAP|TL9) matches all .LOG, txt, .MAP, and .TL9 files

  • !(*.*) matches all files except ones having . in name

Enable extglob first if not enabled:

shopt -s extglob
heemayl
  • 39,294
  • 7
  • 70
  • 76
0

You could also use the find command to list files with extension MAP, LOG, TL9or without any extension at all.

#!/bin/bash

files=`find . -type f -regex ".*[\.LOG|\.MAP|\.TL9]" -o ! -name "*.*"`

for file in $files
do
  echo $file
done
Cyclonecode
  • 29,115
  • 11
  • 72
  • 93