Home > Back-end >  How to get full path of last modified file in directory including nested directories?
How to get full path of last modified file in directory including nested directories?

Time:01-25

How would I modify this code to give me the full file path of the last modified file in the code directory, including nested sub-directories?

# Gets the last modified file in the code directory.
get_filename(){
    cd "$code_directory" || no_code_directory_error # Stop script if directory doesn't exist.
    last_modified=$(ls -t | head -n1)
    echo "$last_modified"
}

CodePudding user response:

  1. Use find instead of ls, because the use of ls is an anti-pattern.
  2. Use a Schwartzian transform to prefix your data with a sort key.
  3. Sort the data.
  4. Take what you need.
  5. Remove the sort key.
  6. Post process the data.
find "$code_directory" -type f -printf '%T@ %p\n' |
  sort -rn |
  head -1 |
  sed 's/^[0-9.]\  //' |
  xargs readlink -f

CodePudding user response:

You can use the realpath utility.

# Gets the last modified file in the code directory.
get_filename(){
    cd "$code_directory" || no_code_directory_error # Stop script if directory doesn't exist.
    last_modified=$(ls -t | head -1)
    echo "$last_modified"
    realpath "$last_modified"
}

Output:

blah.txt
/full/path/to/blah.txt

CodePudding user response:

ls -t sort by modification time and if you want first one you can add | head -1, R helps you recursively sort files, I think the only tips here is ls -tR doesn't stack all files then sort them, so you can use

find . -type f -printf "%T@ %f\n" | sort -rn > out.txt
  •  Tags:  
  • Related