ファイルの数だけ処理を繰り返すサンプル(sh bash版)です。foreachを使ったcsh tcsh版は こちら
繰り返し+正規表現でファイルを絞り込むサンプルはこちらです。

サンプル1 sample1.sh

#/bin/sh
# ファイル名をlsで取得(ファイル名の昇順)しwhileで回す
ls -1 | while read line
do

  # 処理を記述(例:ファイル名をフルパスでecho)
  echo `pwd`/$line

done

解説

まず、lsに「-1」オプションをつけると、ファイルが1行に1つずつ表示されます。

$ ls -1
20131031.dat
aaa
bbb
HOGE20131031.dat
hogehoge.sh

この「ls -1」をwhileコマンドに渡すと、1行ずつファイル名が変数に設定されて繰り返し処理ができます。
ls -1 | while read line
do
  処理を記述、「$line」でファイル名を活用できます。
done

フルパスがほしい場合は、今回のサンプルのように「pwd」の結果を結合してもよいですし、「ls /hogehoge/* -1」のようにフルパスに*を付けてもよいです。

おまけ

# ファイル名の降順でソート
ls -1r | while read line

# タイムスタンプの昇順(新しい順)でソート
ls -1t | while read line

# タイムスタンプの降順(古い順)でソート
ls -1tr | while read line
他にもソートのオプションはいろいろあるので試してみましょう


繰り返し+正規表現でファイルを絞り込むサンプル

サンプル2 sample2.sh

#!/bin/sh

# ファイル名をlsで取得+grepで絞り込み
ls -1 | grep -E '^2[0-9]{3}[01][0-9][0-3][0-9](HOGE|MOGE)\.dat$' | while read line
do

  # 処理を記述(例:ファイル名をフルパスでecho)
  echo `pwd`/$line

done
変更点
ls -1 | while read line
↓
ls -1 | grep -E '^2[0-9]{3}[01][0-9][0-3][0-9](HOGE|MOGE)\.dat$' | while read line
「ls -1」の結果をハイプ「|」で「grep -E」に渡して絞り込むという作りになっています。
「grep」はテキストの検索コマンドで「E」オプションは拡張正規表現を使うという意味です。
ちょっと複雑な正規表現を使う場合は「E」オプションが必要になります。
今回使用した正規表現は「20130101」などの年月日から始まり、「HOGEまたはMOGE」に拡張子がdatで終わるファイル名だけ出力する用になっています。
以下にサンプルの実行結果を示します。
サンプル1の実行結果
$ ./sample1.sh
/home/hoge/shellsample/01HOGE20131031.dat
/home/hoge/shellsample/20130101HOGE.dat
/home/hoge/shellsample/20130101MOGE.dat
/home/hoge/shellsample/20131031.dat
/home/hoge/shellsample/aaa
/home/hoge/shellsample/bbb
/home/hoge/shellsample/HOGE20131031.dat
/home/hoge/shellsample/hogehoge.sh
/home/hoge/shellsample/MOGE20121031.dat
/home/hoge/shellsample/mogemoge.sh
サンプル2の実行結果
$ ./sample2.sh
/home/hoge/shellsample/HOGE20131031.dat
/home/hoge/shellsample/MOGE20121031.dat
最終更新:2013年11月02日 23:29
添付ファイル