#navi(../)
* ファイルのサイズを取得する [#w52af694]
ファイルのサイズ(バイト数)をls, awk, wc, cutコマンドを使用して取得するサンプルシェルスクリプトです。
#contents
#htmlinsertpcsp(linux_ads_top.html,linux-sp.html)
* ls, awk, wc, cutを使用してファイルサイズを取得する [#s1236dc5]
以下にls + awk, wc + cut コマンドを使用してファイルサイズを取得するサンプルシェルスクリプトを記します。
#ref(filesize.sh)
#/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 + awk の説明 [#zfe5e16d]
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 + cut の説明 [#a8b4ab07]
wc -c によりバイトするを表示させます。~
一緒にファイル名も表示されるのでcutコマンドで1番めの表示させています。
$ wc -c /etc/hosts
158 /etc/hosts
$ wc -c /etc/hosts | cut -d' ' -f1
158
cutコマンドについては、以下の資料を参考にしてください。
-[[逆引きUNIXコマンド/指定したフィールドを取り出す・cut]]
以上、ファイルサイズ(バイト数)を取得するサンプルシェルスクリプトでした。
#htmlinsertpcsp(linux_ads_btm.html,linux-sp.html)