4

this command allows me to login to a server, to a specific directory from my pc ssh -t xxx.xxx.xxx.xxx "cd /directory_wanted ; bash"

How can I then do this operation in that directory. I want to be able to basically delete all files except the N most newest. find ./tmp/ -maxdepth 1 -type f -iname *.tgz | sort -n | head -n -10 | xargs rm -f

Community
  • 1
  • 1
HattrickNZ
  • 4,373
  • 15
  • 54
  • 98

2 Answers2

7

This command should work:

ls -t *.tgz | tail -n +11 | xargs rm -f

Warning: Before doing rm -f, confirm that the files being listed by ls -t *.tgz | tail -n +11 are as expected.

How it works:

ls lists the contents of the directory.-t flag sorts by modification time (newest first). See the man page of ls

tail -n +11 outputs starting from line 11. Please refer the man page of tail for more detials.

If the system is a Mac OS X then you can delete based on creation time too. Use ls with -Ut flag. This will sort the contents based on the creation time.

gaganso
  • 2,914
  • 2
  • 26
  • 43
1

You can use this command,

ssh -t xxx.xxx.xxx.xxx "cd /directory_wanted; ls -t *.tgz  | tail -n
+11 | xargs rm -f; bash"

In side quotes, we can add what ever the operations to be performed in remote machine. But every command should be terminated with semicolon (;)

Note: Included the same command suggested by silentMonk. It is simple and it is working. But verify it once before performing the operation.

Krishna
  • 179
  • 3
  • 6