Am trying to cut the three columns using awk command.

-rwxrwxr-x 1 rouser users 33 Oct 19 05:20 b.sh

Am using this below line to cut the 33 Oct 19 05:20 values.

z=`ls -l b.sh | awk '{print $6,$7,$8 }'`
echo $z

z will give the result as 33 Oct 19 05:20 .

What my question is, I want date, month, year in this format 19/10/2016.
what should I do??
kindly help me as soon as possible.


A few notes about parsing ls output:

  • the format depends on the locale. If you need to parse it, you need to fix the locale to something known, typically C
  • in the ls -l output, as the user name and group name appear before the date and may contain spaces (rare in practice though), you can't rely on the date being always on the 6th field. It's better to use ls -n to use numeric uid/gid instead (or -o, -g with implementations that have them).
  • if the file is of type directory, ls -l file would list its content. You want the -d option (LC_ALL=C ls -nd -- "$file" so far).
  • if the file name (or the target of the symlink for files of type symlink) contains newline characters, then you need to make sure you only consider the first line of the output

    LC_ALL=C ls -nd -- "$file" | awk '{print $6,$7,$8; exit}'
  • In the C locale, the format of the modification time varies depending on whether the file was last modified in the last 6 months or not (or in the future). So you can get Jun 14 09:18 or Feb 4 2014 or Jan 1 2017 if run on 2016-11-09. If a year is not given, then you can't assume the year is the current year. For instance, if you run it in January and get a Dec 24 23:59, that's the December of last year.

It's still possible to work it out like:

LC_ALL=C ls -dn -- "$file" | awk -v now="$(date +%m:%Y)" '{
  m=$6; d=$7; y=$8
  m = index("--JanFebMarAprMayJunJulAugSepOctNov", m) / 3
  if (y ~ /:/) {
    split(now, a, ":")
    y = a[2]
    if (m > a[1]) y--
  printf "%02d/%02d/%04d\n", d, m, y

But best would be to get the time in the right format from the start. With zsh, you can use its stat builtin:

zmodload zsh/stat
stat -LF %d/%m/%Y +mtime -- $file

On a GNU system, you can do:

date -r "$file" +%d/%m/%Y

(though for symlinks, it gives you the modification time of the target).


find -- "$file" -prune -printf '%Td/%Tm/%TY\n'

on BSDs:

stat -t %d/%m/%Y -f %Sm -- "$file"

Or using perl for portability:

perl -MPOSIX -le '@s = lstat shift or die "lstat: $!";
  print strftime "%d/%m/%Y", localtime $s[9]' -- "$file"

If you want to use ls, you can do this: ls -l --time-style=+%d/%m/%Y

  • That's GNU-specific though. Among GNU tools date -r, find -printf or stat would be more appropriate. – Stéphane Chazelas Nov 9 '16 at 16:28

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.