brewedbits.dev

Personal blog with guides and news on selfhosting, Linux and AI, from the Netherlands

nextDash nextdash --aboutYour bookmarks. Your terminal. checks your links knows your Docker host one container, no cloudLive demo →nextdash.cc ↗

Tip: find -exec mv -t moves many files with one mv command

Find
~/tips/tip-find-exec-mv-t

find /srv/app -name '*.log' -mtime +30 -exec mv -t /srv/old-logs {} +

Moves all the files find selects into one folder with a handful of mv calls instead of one per file.

With -exec ... {} +, find packs many names into one command, which is much faster than one command per file. There’s a rule though: the {} has to come right before the +.

That’s a problem for mv and cp, which want the destination last. GNU coreutils solves it with -t, which names the target folder up front:

mkdir -p /srv/old-logs
find /srv/app -name '*.log' -mtime +30 -exec mv -t /srv/old-logs {} +

find adds the file names at the end, and mv knows where they go because of -t. cp -t and ln -t work the same way.

Without -t you’d write -exec mv {} /srv/old-logs \;, which starts a new mv for every single file. With a few thousand logs, I’d take the -t version every time.

Watch for two things. All files land in one flat folder, so two files called app.log from different subfolders will overwrite each other; add -n to mv to never overwrite, or --backup=numbered to keep both. And if the target folder sits inside the tree you’re searching, find can run into the files it just moved. Keep the target outside, or exclude it with -prune.

Further reading: find(1) manual page, mv invocation, GNU coreutils

More Find tips find / -maxdepth 1 -fstype proc find /backup -name '*.gz' ! -exec gzip -t {} \; -print 2>/dev/null find /srv/downloads -type f -size +100M -size -1G -exec ls -lh {} + find /srv/data -depth -print find /srv -xdev -samefile /srv/downloads/movie.mkv All Find tips (46) All topics

Link