ファイルのサイズ(バイト数)をls, awk, wc, cutコマンドを使用して取得するサンプルシェルスクリプトです。
以下にls + awk, wc + cut コマンドを使用してファイルサイズを取得するサンプルシェルスクリプトを記します。
#/bin/bash
function usage {
echo Usage: `basename $0` file
exit 1
}
if [ $# -ne 1 ]; then
usage
fi
if [ -f $1 ]; then
# ls and awk command
size=`ls -l $1 | awk '{ print $5; }'`
echo "$1 = $size bytes"
# wc command
size=`wc -c $1 | cut -d' ' -f1`
echo "$1 = $size bytes"
else
echo "$1 file not found."
fi
実行結果は以下の通りです。
$ chmod +x filesize.sh $ ./filesize.sh /etc/hosts /etc/hosts = 158 bytes ← ls + awk /etc/hosts = 158 bytes ← wc + cut
ls -lコマンドによりファイルの情報が表示されます。
先頭から5番目にファイルサイズが表示されているので、awkにより5番目($5)を表示させています。
$ ls -l /etc/hosts
-rw-r--r--. 1 root root 158 6月 7 2013 /etc/hosts
[sakura@centos7 ~]$ ls -l /etc/hosts | awk '{ print $5; }'
158
wc -c によりバイトするを表示させます。
一緒にファイル名も表示されるのでcutコマンドで1番めの表示させています。
$ wc -c /etc/hosts 158 /etc/hosts $ wc -c /etc/hosts | cut -d' ' -f1 158
cutコマンドについては、以下の資料を参考にしてください。
以上、ファイルサイズ(バイト数)を取得するサンプルシェルスクリプトでした。