Thursday, October 30, 2014

Delete 10 newest files in Linux

Delete 10 newest files in Linux

The code you'd want to include in your script is
 rm -f $(ls -1t /path/to/your/logs/ | tail -n +11)
The -1 (numeric one) option prints each file on a single line, to be safe. The -f option to rm tells it to ignore non-existent files for when ls returns nothing.
Or use the below command
ls -d -1tr /path/to/folder/* | head -n -10 | xargs -d '\n' rm -f

Delete latest 3 files:
rm -f $(ls -1t ./ | head -3)   

Find a folder
Just find directories and skip file names pass the -type d option as follows:
find  / -type d -name "apt" -ls

locate httpdocs


Gives the time stamp

date +%Y%m%d -s "20081128"
date +%T -s "11:18:00"

Stat file.txt

newest=$(find subdir -newer timestamp -printf "%A%p\n" |
                sort -n |
                tail -1 |
                cut -d: -f2- )
     touch -r "${newest:-timestamp}" timestamp
The command above works by generating a list of the timestamps and names of all the files which are newer than the timestamp. The sort, tail and cut commands simply pull out the name of the file with the largest timestamp value (that is, the latest file). The touch command is then used to update the timestamp,
The "${newest:-timestamp}" expression simply expands to the value of $newest if that variable is set, but to timestamp otherwise. This ensures that an argument is always given to the ‘-r’ option of the touch command.

No comments:

Post a Comment