command line - Move only the last 8 files in a directory to another directory - Ask Ubuntu
i'm trying move last 8 files documents directory directory, don't want move them one-by-one specific directory. possible move them substitute of tail command, directories instead of files? mean i'd tail -8 ./documents | mv ./anotherdirectory or mv tail -8 ./documents ./anotherdirectory.
in fact, i'm looking clever way move last 8 files (as listed in ls) (without typing out each name) other directory. suggestions?
you can use for, loops on files in ordered way, , allows avoid parsing output of find or ls, avoid issues spaces , other special characters in filenames. many @muru improving :)
i=0; j=$(stat ~/documents/* --printf "%i\n" | wc -l); k in ~/documents/*; if (( (j - ++i) < 8 )); echo mv -v "$k" ~/anotherdirectory; fi; done test first echo, remove echo move files.
as script:
#!/bin/bash i=0 j=$(stat ~/documents/* --printf "%i\n" | wc -l ) k in ~/documents/*; if (( (j - ++i) < 8 )); echo mv -v -- "$k" ~/anotherdirectory fi done again, remove echo after testing move files real
explanation
i=0telling shell start iterating @ 0j=$(stat ~/documents/* --printf "%i\n" | wc -l )setting variablejinteger equal total number of files in directory. serg's answer own question on how count files reliably no matter characters names containdo if (( (j - ++i) < 8 ))each iteration of loop, test whether outcome ofjminus number of times loop has been run less 8 , if thenmv -v -- "$k" ~/anotherdirectorymove file new directory
Comments
Post a Comment