LoginSignup
3

More than 3 years have passed since last update.

ShellScript書く時の小ネタ

Last updated at Posted at 2019-10-09

すぐ忘れることが多い小ネタをまとめていきます。多分随時更新します。

ファイル存在チェック

if [ -e ${FILE_NAME} ]; then
    # DO SOMETHING
fi
存在しない場合は否定
if [ ! -e ${FILE_NAME} ]; then
    # DO SOMETHING
fi

ファイルを空にする

: > ${FILE_NAME}

対象ディレクトリ内を一覧する

for file in `\find ${DIR_NAME}`; do 
    echo $file
done
探索の深さ指定
for file in `\find ${DIR_NAME} -maxdepth 1`; do 
    echo $file
done
ファイルのみをリストするよう指定(ディレクトリ除外)
for file in `\find ${DIR_NAME} -type f`; do 
    echo $file
done

ディレクトリ内のファイルのみ削除する

find ${DIR} -type f | xargs rm -f

2ファイルを比較して差分を抽出

diffだと色々入ってしまってまた加工が大変なので


awk -v "result_file=${RESULT_FILE}" 'BEGIN {FS = "\n"} NR == FNR {a[$1]=1; next}
{
    if ($1 in a) {
        print "" >> "/dev/null"
    }
    else {
        print $1 >> result_file
    }
}' ${FILE_NAME_1} ${FILE_NAME_2}

awkに変数を渡す

-vオプションを利用する
awkコマンドの-vオプションに続けてawkで用いる変数=代入する値value(もしくはシェル変数)を記述

awk -v hoge=value '{print $0 > hoge}' file

thanks

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
3