LoginSignup
2
3

More than 5 years have passed since last update.

ファイルのタイムスタンプを取得する(SunOS 5.10)

Last updated at Posted at 2012-12-26

これ。

shell
TIMESTAMP=`ls -E hoge.txt | sed -e 's/  */ /g' | cut -d " " -f 6-7 | cut -c 1-19`

echo $TIMESTAMP

以下、解説っぽいもの

1. SunOSだと --time-style や --full-time オプションが使用できない。

ls の -E オプションでタイムスタンプを ISO 8601形式に固定して出力できる。

-bash-3.00$ ls -E hoge.txt
-rw-r--r--    1 foo    users        0 2010-08-06 13:45:15.341837000 +9000 hoge.txt

2. このままだと、半角スペースの数がまちまちで必要な文字列だけをカットするのが面倒なので、区切り文字として整えてやる。

「sed -e 's/ */ /g'」で複数の半角スペースを1つに置換します。

  • 置換対象の正規表現には「△△*」半角スペース2つ入ってます。
-bash-3.00$ ls -E hoge.txt | sed -e 's/  */ /g'
-rw-r--r-- 1 foo users 0 2010-08-06 13:45:15.341837000 +9000 hoge.txt

3. 区切り文字が半角スペース1個だということがはっきりしたので、cutコマンドで区切り文字に半角スペースを指定して、必要なフィールド(区切り文字で区切った何番目の文字列か)を指定してやる。

「cut -d " " -f 6-7」がそれ。日付と時刻が入っているのは6、7番目のフィールド。

-bash-3.00$ ls -E hoge.txt | sed -e 's/  */ /g' | cut -d " " -f 6-7
2010-08-06 13:45:15.341837000

4. ここまででもいいのだけど、ナノ秒は使用しなかったので切り落とした。

「cut -c 1-19」。1~19文字目を抜き出す。

-bash-3.00$ ls -E hoge.txt | sed -e 's/  */ /g' | cut -d " " -f 6-7 | cut -c 1-19
2010-08-06 13:45:15

というわけで、最終的に「yyyy-mm-dd hh:mi:ss」形式のタイムスタンプが取得できました。めでたしめでたし。

※この記事の内容は2010年8月に自分で書いた文章を転記したものです。

2
3
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
2
3