Iterate over specific file extension in a dir in shell script

Sometimes we need to iterate over all files of a specific file extension using a bash script. This can be used to convert one type of file to another or any other use case. Here are some approaches for iterating over .txt files in a directory tmp.

Using ls or find in sub-shell

You can use ls in a sub shell to get the desired list of .txt files.

#!/bin/bash
## cd to destination dir
cd ~/data/tmp
FILES=$(ls *.txt)
for i in $FILES ; do
  echo $i
done

Or you can use find command in sub-shell find .txt files.

#!/bin/bash
## cd to destination dir
cd ~/data/tmp
FILES=$(find . -name "*.txt")
for i in $FILES ; do
  echo $i
done

Approach 2

#!/bin/bash
## cd to destination dir
cd ~/data/tmp
for i in *.txt ; do
  echo $i
done

Approach 3

#!/bin/bash
## cd to destination dir
cd ~/data/tmp
FILES=*.txt
for i in $FILES ; do
  echo $i
done
Share this article: share on Google+ share on facebook share on linkedin tweet this submit to reddit

Comments

Click here to write/view comments