前回、ファイルの操作や検索について紹介した。
今回は、目的のファイルを探したり、もう少し実践で使う処理について紹介する。

以下の構成を用いる。

1
2
3
4
5
├── sample1.txt
├── sample2.txt
└── temp1
├── depthfile1.txt
└── depthfile2.txt

find

ディレクトリやファイルを見つけるコマンド。

  • 例: depthfile1.txt というファイルを探したい。

    1
    2
    # find . -name "depthfile1.txt"
    ./temp1/depthfile1.txt
  • 例: ファイルの一覧を出したい

    1
    2
    3
    4
    5
    # find . -type f
    ./sample1.txt
    ./sample2.txt
    ./temp1/depthfile1.txt
    ./temp1/depthfile2.txt
  • 例: ディレクトリの一覧を出したい

    1
    2
    3
    # find . -type d
    .
    ./temp1
  • 例: ファイルの一覧を出したい。ただし、sample1.txt という文字が入っているファイルは除外する

    1
    2
    3
    4
    # find . ! -name "sample1.txt" -a -type f
    ./sample2.txt
    ./temp1/depthfile1.txt
    ./temp1/depthfile2.txt

xargs

標準入力を読み込み、引数にして指定したコマンドを実行することができる。

例えば、最初に表示した構成で、ファイルを全て消したい場合、一つ一つrm filename を渡して消せば消えるが、4回実行する必要があるが、findとxargsを組み合わせると1回でファイルを削除することができる。

1
2
3
4
5
6
7
8
9
10
11
12
まずは確認
# find . -type f
./sample1.txt
./sample2.txt
./temp1/depthfile1.txt
./temp1/depthfile2.txt

実行
# find . -type f | xargs rm

消えていることを確認
# find . -type f

このように組み合わせることで出来ることが増える。