I faced some issue while i list all the files in my directory , i would like to print or fetch just the file which is before the last file was modified
server:cd user/local
server/user/local/: ls -ltrh
-rw-r--r-- 1 Pepe staff 0B Nov 7 13:40 1.txt
-rw-r--r-- 1 Pepe staff 0B Nov 7 13:40 2.txt
-rw-r--r-- 1 Pepe staff 0B Nov 7 13:40 3.txt
-rw-r--r-- 1 Pepe staff 0B Nov 7 13:58 5.txt
-rw-r--r-- 1 Pepe staff 9B Nov 7 14:25 6.txt
I hope i can have the result 5.txt
Any idea ?
CodePudding user response:
This is a fairly complex-looking pipeline, but each piece is pretty straightforward:
stat -c '%Y:%n' * | sort -t: -n | cut -d: -f2- | tail -2 | head -1
check your stat
man page to see if your version has the -c
option.
CodePudding user response:
Here's an adaptation of the method in https://stackoverflow.com/a/73613596/3387716
It finds the n
th last modified file and puts its "basename" in the variable var
:
#!/bin/bash
n=2
IFS='' read -r -d '' var < <(
find user/local -maxdepth 1 -type f -printf '%T@ %p\0' |
sort -z -nrt ' ' -k1,1 |
awk -F '/' -v n="$n" '
BEGIN { RS = ORS = "\0" }
NR == n { print $NF }
'
) || {
echo "Not enough files in dir" 1>&2
exit 0
}
echo "$var"