0

let suppose I have folders with names af32, af42, af, and I want to print the last modification date of all folders whose have af* pattern for example . I writed shell that will take folder or files as parameter and return modification date for that folder .

stat -c %y "$1"

this code will return the last modification date to folder . but how can I apply this code to more than one folder whose have same pattern in their name

Muh
  • 45
  • 4

2 Answers2

1

You can use find to search recursively in search_folder/ for directories (-type d) matching a specific pattern glob (e.g. -name 'af*'):

find search_folder/ -type d -name 'af*' -exec stat -c '%y %n' '{}' \;

This will then execute (-exec ... \;) the command stat -c '%y %n' '{}' on each of the search results, replacing {} with the result path, starting with the given search_folder/.

Note that I modified your stat output to include the file name/path %n in the result, because otherwise you wouldn't see what file each modification date belongs to.

Byte Commander
  • 105,631
  • 46
  • 284
  • 425
  • yes thank you for your reply . the code working fine but for one folder. if I have folders with name af1,af2,af3 that code will give me result just for one folder – Muh Jun 06 '18 at 14:21
  • 1
    You have to replace `search_folder/` with a parent directory that contains all the folders of which you want the info. Then it will recursively search inside that location and run the `stat` command on all matching folders below it. – Byte Commander Jun 06 '18 at 14:32
  • 1
    More efficient with: `-exec … +` – dessert Jun 06 '18 at 16:31
1

You can use shell globbing as follows:

stat -c %y af*/

af*/ matches every directory in the current directory beginning with “af”.
If this throws an error like

bash: /usr/bin/stat: Argument list too long

use this printf approach instead:

printf '%s\0' af*/ | xargs -0 stat -c %y

Example run

You might want to add %n to stat’s output…

$ ls
af  af32  af42  bf  cg45
$ stat -c %y af*/
2018-06-05 18:59:55.355277977 +0200
2018-06-04 19:01:28.968869600 +0200
2018-06-06 18:58:15.968639269 +0200
$ stat -c '%y %n' af*/
2018-06-05 18:59:55.355277977 +0200 af/
2018-06-04 19:01:28.968869600 +0200 af32/
2018-06-06 18:58:15.968639269 +0200 af42/
dessert
  • 39,392
  • 12
  • 115
  • 163