Search code examples
grepcommand-line-argumentslsmvsolaris-10

Listing last 5 recent files and move them to another directory


I'm trying to achieve a one line command to list the last 5 new files within a directory and move those files to another location. By now I can list them, but haven't find the way to move them, any tip?

ls -1t *.txt | head -5

I have:

$ ls -1t *.txt | head -5
record_-_53810.20160511_-_1053+0200.txt
record_-_53808.20160511_-_1048+0200.txt
record_-_53570.20160510_-_1508+0200.txt
record_-_53568.20160510_-_1503+0200.txt
record_-_53566.20160510_-_1458+0200.txt

Solution

  • Just pipe to xargs:

    ls -1t *.txt | head -5 | xargs -i mv {} another_dir/
    

    Or use the expansion itself:

    mv $(ls -1t *.txt | head -5) another_dir/
    

    Or even loop:

    while IFS= read -r file;
    do
       mv "$file" another_dir/
    done < <(ls -1t *.txt | head -5)