0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

findとsedを一緒に使うshellスクリプト

Posted at

実現したいこと

  • プロジェクトフォルダにある全てのtest_で始まり.pyで終わるファイルをfindで抽出
  • findで抽出された./server/sample.pyのPathをserver/sample.pyにsedで置換(./の部分を消す)

結論

find . -name '*.py' -name 'test_*' | sed -e "s/\.\///"

解説

findの解説

findの後の.は探すディレクトリがカレントディレクトリであることを示す。
-nameで探すファイル名の条件を指定できる(-nameを追加していくとAND検索になる)
1つ目の'*.py'.pyで終わるファイル
2つ目の'test_'test_で始まるファイル

sedの解説

sはsコマンドは正規表現で置換処理をする宣言。
"s/[置換前]/[置換後]/[オプション(任意)]"となる

今回の場合は、
[置換前]の部分が\.\/を示している。
バックスラッシュ(\)は./にエスケープが必要なため入っている。

[置換後]の部分は無し。理由は今回は./の部分を消したいから。

[オプション(任意)]も今回はなし。

参考記事: (sed コマンド)[https://hydrocul.github.io/wiki/commands/sed.html]

どう使えるのか?

python3 -m unittest [テストファイルへのPATH]で自動でプロジェクトフォルダ内の全てのユニットテストを実行したかった。

実際のシェルスクリプト

py-test.sh
# !/usr/bin/env bash

# find all test files 
testFiles=($(find . -name '*.py' -name 'test_*' | sed -e "s/\.\///"))

# test each file
for file in ${testFiles[@]}
do
    echo "TEST: $file"
    python3 -B -m unittest $(echo $file)
    echo 
done

補足

-Bpycacheを生成しないコマンドオプション

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?