Search code examples
linuxbashterminalfedorastat

How can i format the output of stat expression in Linux Gnome Terminal?


I am really newbie in Linux(Fedora-20) and I am trying to learn basics I have the following command

echo "`stat -c "The file "%n" was modified on ""%y" *Des*`"

This command returns me this output

The file Desktop was modified on 2014-11-01 18:23:29.410148517 +0000

I want to format it as this:

The file Desktop was modified on 2014-11-01 at 18:23

How can I do this?


Solution

  • You can't really do that with stat (unless you have a smart version of stat I'm not aware of).

    With date

    Very likely, your date is smart enough and handles the -r switch.

    date -r Desktop +"The file Desktop was modified on %F at %R"
    

    Because of your glob, you'll need a loop to handle all files that match *Des* (in Bash):

    shopt -s nullglob
    for file in *Des*; do
        date -r "$file" +"The file ${file//%/%%} was modified on %F at %R"
    done
    

    With find

    Very likely your find has a rich -printf option:

    find . -maxdepth 1 -name '*Des*' -printf 'The file %f was modified on %TY-%Tm-%Td at %TH:%TM\n'
    

    I want to use stat

    (because your date doesn't handle the -r switch, you don't want to use find or just because you like using as most tools as possible to impress your little sister). Well, in that case, the safest thing to do is:

    date -d "@$(stat -c '%Y' Desktop)" +"The file Desktop was modified on %F at %R"
    

    and with your glob requirement (in Bash):

    shopt -s nullglob
    for file in *Des*; do
        date -d "@$(stat -c '%Y' -- "$file")" +"The file ${file//%/%%} was modified on %F at %R"
    done