0

Basically my requirement is to find 10 latest logs and compress it into zip. I have tried command ls -Lt | head -10 | zip log.zip *.log, but output is not matched.

  • Did you consider using 'logrotate' with a dedicated schedule? You are able to specify how old the files may get before being compressed. – gerhard d. Mar 14 at 8:17
1

First take backup

You should try:

ls -Lt | head -10 | xargs zip log.zip 

Your command

zip log.zip *.log

is trying to compress every file in the current directory which is ending with .log, it is not taking file names from STDIN.

If your directory has mixed files, i.e. files other than log files, then you can try:

ls -Lt *.log | head -10 | xargs zip log.zip
  • thanks , ls -Lt | head -10 | xargs zip log.zip here zip is created in same directory i want that zip is goes to different directory so how can specify with this command] – Prabhat Jaiswal Mar 14 at 9:51
  • Instead of log.zip use the absolute path like /home/username/...../log.zip. – Prvt_Yadav Mar 14 at 10:04
  • 1
    be warned that if any of the filenames (ever) contain spaces, tabs, or newlines, then they will be mangled and lost in the current pipeline. – Jeff Schaller Mar 14 at 19:13
2

To safely select the 10 most recent (plain) files in the current directory, I would recommend zsh, since it can safely, natively, select files based on modification time:

zsh -c 'zip log.zip *.log(.om[1,10])'

This uses two of zsh's wildcard ("glob") qualifiers and a subscripting operator:

  • *.log( ... ) -- this starts the wildcard off with *.log, which will select every1 file in the current directory that ends with .log, filtered by the following criteria
  • . -- this filters the resulting list to include only plain files
  • om -- this sorts ("orders") the resulting list by modification time, most recent first
  • [1,10] -- this narrows the resulting list by selecting elements 1 through 10 (the ten most recent files)

Once zsh has generated the 10 most recent plain files, it hands those to the zip command.


Footnotes:

  1. by default, zsh will not select hidden (dot) files, such as .foo.log; if you have such files and wish to select them, you can include the D glob qualifier (*.log(.Dom[1,10])) or set the GLOB_DOTS option (with setopt globdots).
0

Tried with below command

ls -ltrh| awk '$1 ~ /-rw/{print $0}'|sed -n '1,10p'| awk '{print "zip" " " $NF".zip" " " $NF}'| sh
  • Please don't try to parse ls. Besides the usual trouble, what if the file(s) aren't writable by the user-- causing the /-rw/ to fail? – Jeff Schaller Mar 14 at 19:05

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.