I am trying to find all files after certain modified date from a directory in the sorting order of modified date using shell script. This is one of the part of my current shell script.
Condition contains two steps: 1) Fetch files from a directory after certain modified date. 2) sort the files by modified date.
Current directory contains files like this:
Mar 28 11:14 file_H_1
Apr 2 16:37 file_K_2
Apr 1 21:43 file_H_3
Apr 16 19:16 file_H_4
Apr 16 21:00 file_H_5
Apr 16 12:00 file_L_6
Apr 9 14:08 file_B_7
Apr 4 00:39 file_H_8
Apr 4 00:39 file_H_9
Apr 4 00:39 file_C_10
Apr 4 00:39 file_H_11
Mar 27 14:39 file_H_12
I want final output as a list of files with modified date after "2018-04-09 00:00:00" and in order by modified date. OUTPUT should be:
file_B_7
file_L_6
file_H_4
file_H_5
I tried this:
1) For getting files after certain modified date
find . -type f -newermt "2018-04-09 00:00:00"
OUTPUT of this:
file_L_6
file_H_5
file_B_7
file_H_4
2) order the files on modified date
ls -lt
OUTPUT of this
Apr 16 21:00 file_H_5
Apr 16 19:16 file_H_4
Apr 16 12:00 file_L_6
Apr 9 14:08 file_B_7
Apr 4 00:39 file_H_8
Apr 4 00:39 file_H_9
Apr 4 00:39 file_C_10
Apr 4 00:39 file_H_11
Apr 2 16:37 file_K_2
Apr 1 21:43 file_H_3
Mar 28 11:14 file_H_1
Mar 27 14:39 file_H_12
But I am struggling to combine these two conditions.
I tried this also but it is sorting on file name not on modified date:
find . -type f -newermt "2018-04-9 00:00:00" | sort -n | while read file_name; do
echo file=$file_name
done
OUTPUT of this:
file_B_7
file_H_4
file_H_5
file_L_6
Please suggest some solution.
Use a combination of find
and ls -t
with a pipe:
find -type f -newermt "2018-04-09 00:00:00" | xargs ls -tl
xargs
gives the output of find
to ls
.
In case some of your filenames have spaces, use this:
find -type f -newermt "2018-04-09 00:00:00" -print0 | xargs -0 ls -tl
-print0
option allows to use the filename deleimiter as \\0
. xargs
expects this delimiter with the option -0
.
Note that you can use ls -ltr
if you want the reverse time order.
In any case, you shouldn't parse the result of ls
( Ref ).
Instead of using xargs ls
you can also insert the find output directly into the ls
command line:
ls -tr `find -type f -newermt "2018-04-09 00:00:00"`
Note that both approaches would fail if not all the filenames fit into one command line - xargs ls
silently by not sorting correctly, this here with an error message.
这应该可以解决问题。
ls -t | egrep "$(find * -maxdepth 0 -type f -newermt "2018-04-9 00:00:00" -print | sed 's/|/\\|/g' | tr '\n' '|' | sed 's/|$//')"
尝试这个..
ls -t | find . -type f -newermt "2018-04-09 00:00:00"
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.