简体   繁体   中英

Moving files with a specific modification date; "find | xargs ls | grep | -exec" fails w/ "-exec: command not found"

Iam using centos 7

If I want to find files that have specific name and specific date then moving these files to another folder iam issuing the command

find -name 'fsimage*' | xargs ls -ali | grep 'Oct 20' | -exec mv   {}  /hdd/fordelete/  \;

with the following error

-bash: -exec: command not found xargs: ls: terminated by signal 13

As another answer already explains, -exec is an action for find , you can't use it as a shell command. On contrary, xargs and grep are commands, and you can't use them as find actions, just like you can't use pipe | inside find .

But more importantly, even though you could use ls and grep on find 's result just to move files older than some amount of time, you shouldn't . Such pipeline is fragile and fails on many corner cases, like symlinks, files with newlines in name, etc.

Instead, use find . You'll find it quite powerful.

For example, to mv files modified more than 7 days ago, use the -mtime test :

find -name 'fsimage*' -mtime +7 -exec mv '{}' /some/dir/ \;

To mv files modified on a specific/reference date , eg 2017-10-20 , you can use the -newerXY test :

find -name 'fsimage*' -newermt 2017-10-20 ! -newermt 2017-10-21 -exec mv '{}' /some/dir/ \;

Also, if your mv supports the -t option (to give target dir first, multiple files after), you can use {} + placeholder in find for multiple files, reducing the total number of mv command invocations (thanks @CharlesDuffy):

find -name 'fsimage*' -mtime +7 -exec mv -t /some/dir/ '{}' +

the -exec as you wrote it is quite meaningless, moreover it seems you are mixing find syntax with shell oe (-exec as you wrote it should be passed to find)

there are probably more concise ways of doing, but this should do what you expect:

 find  -name 'fsimage*' -type f  | xargs ls -ali  | grep 'Oct 20' | awk '{ print $NF }' | while read file; do  mv "$file" /hdd/fordelete/  ; done

nevertheless, you should take care of not just copy/paste things you do not really understand from the web, you may wreck you system...

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM