0

I'm trying to find the path to the latest edited file in a subdirectory matching a certain patern. For that I want to use a bash script to get the file path and then use it for a bunch of actions.

So for exemple i would have a tree like this:

Directory/
   dir 1.0/
      fileIwant.txt
      fileIdont.txt
   dir 2.0/
      fileIwant.txt
      fileIdont.txt
   dir 2.1/
      fileIwant.txt
      fileIdont.txt

So in this case, I would want to find the latest "fileIwant.txt" (probably the one in "dir 2.1" but maybe not). Then I want to store the path of this file to copy it, rename it or whatever.

I found some scripts to find the latest in current directory but I didn't really understood them... So I hoped someone could give me hand.

Thanks !

Edit : Thanks to the diffent answers I ended up with something like this which work perfectly :

filename="fileIwant"
regex=".*/"$filename"-([0-9]+(\.[0-9]+)*).*/"$filename"\.txt"

path="$(find . -regextype awk -regex $regex -type f -printf '%T@ %p\n' | sort -n | cut -f2- -d" " | tail -1)"

(it doesn't exactly match my previous example obviously)

Benoît
  • 13
  • 2

2 Answers2

1

This can easily be done with only two commands:

ls -t Directory/dir*/fileIwant.txt | head -n 1

The command ls with the option -t sorts its results by modification time, newest first, according to the man page.

Pierre François
  • 5,850
  • 1
  • 17
  • 38
1

This will help you,

find /yourpathtosearch -type f -printf "%T@ %p\n" | sort -nr  | head -n 1 | awk '{print $2}'

man command name will give you more details on how to of each commands Eg: man find

user2700022
  • 489
  • 3
  • 19
  • 1
    okay i used this and used the "-regex" flag of the "find" command to match the files I needed and it works like a charm. Thank you. – Benoît May 06 '20 at 13:09