LoginSignup
0
1

More than 5 years have passed since last update.

bash: 対象ディレクトリ以下のファイル一覧を更新時間でソートして取得する

Last updated at Posted at 2018-03-17

やりたいこと

主題。
ただし。.git/.cache といった . から始まるディレクトリ以下のファイルは除外する。

環境

  • Linux (Ubuntu 16.04)
  • Bash

Command

$ find /var/log -type d -name '.*' -prune -o -type f -printf '%T+ %p\n' | sort | tail -n 3
2018-03-17+11:53:37.7748230000 /var/log/dpkg.log
2018-03-17+11:53:37.8845731000 /var/log/apt/term.log
2018-03-17+11:53:37.8965736000 /var/log/apt/history.log

-type d -name '.*' -prune. から始まるディレクトリを除外する。
-type f -printf "%T+ %p\n" でファイルのmodification time付きでファイル一覧を出す。

       -printf format
              True; print format on the standard output, interpreting `\' escapes and `%' directives.  Field widths and precisions can be specified as  with
              the `printf' C function.  Please note that many of the fields are printed as %s rather than %d, and this may mean that flags don't work as you
              might expect.  This also means that the `-' flag does work (it forces fields to be left-aligned).  Unlike -print, -printf does not add a  new‐
              line at the end of the string.  The escapes and directives are:

              %Tk    File's last modification time in the format specified by k, which is the same as for %A.

                     +      Date and time, separated by `+', for example `2004-04-28+22:22:05.0'.  This is a GNU extension.  The time is given in  the  cur‐
                            rent timezone (which may be affected by setting the TZ environment variable).  The seconds field includes a fractional part.

              %p     File's name.

対象ディレクトリを引数に指定できるよう関数化したもの:

function lastmodified() {
    local dir_path=$(readlink -f "$1")

    if [ "${dir_path}" = "" ]; then
        echo "Usage: ${FUNCNAME[0]} DIR_PATH" 1>&2
        return 22
    fi

    \find "$dir_path" -type d -name '.*' -prune -o -type f -printf '%T+ %p\n' | sort
}
0
1
1

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