How to copy the 10 most recent files from one directory to another?

My html files are stored here:

/home/thinkcode/myfiles/html/ 

I want to move the latest 10 files to /home/thinkcode/Test

I still have it. Please correct me. I am looking for one liner!

 ls -lt *.htm | head -10 | awk '{print "cp "$1" "..\Test\$1}' | sh 
+6
source share
3 answers
 ls -lt *.htm | head -10 | awk '{print "cp " $9 " ../Test/"$9}' | sh 
+9
source

Here is a version that does not use ls . It should be less vulnerable to strange characters in file names:

 find . -maxdepth 1 -type f -name '*.html' -print0 \| xargs -0 stat --printf "%Y\t%n\n" \| sort -n \| tail -n 10 \| cut -f 2 \| xargs cp -t ../Test/ 

I used find for two reasons:

1) if there are too many files in the directory, bash will prevent the expansion of the * substitution.

2) Using the -print0 argument to find covers the bash problem of expanding spaces in the file name for multiple tokens.

* In fact, bash uses a memory buffer to expand substitution and environment variables, so it is not strictly a function of the number of file names, but rather the total length of file names and environment variables. Too many environment variables => no wildcard expansion.

EDIT: Some improvements to @glennjackman included. The initial use of find fixed to avoid using a wildcard extension that could fail in a large directory.

+6
source
 ls -lt *.html | head -10 | awk '{print $NF}' | xargs -i cp {} DestDir 

In the above example, DestDir is the destination directory for the copy.

Add -t after xargs to see the commands as they execute. Ie, xargs -i -t cp {} DestDir .

Check out the xargs team for more information.

EDIT: As @DennisWilliamson noted (and will also check the current manual page), select the -i This option is deprecated; use -I instead. This option is deprecated; use -I instead. .

In addition, both solutions presented depend on the file names in questions that do not contain spaces or tabs.

+4
source

Source: https://habr.com/ru/post/915817/


All Articles