0

I am facing problem in zsh scripting. I have group of files in a directory such as:

001_20160223.txt  /delete
001_20161102.txt  /delete
001_20161209.txt  /keep
005_20160502.txt  /delete 
005_20161105.txt  /delete
005_20161206.txt  /keep
009_20160502.txt  /delete
009_20161105.txt  /delete
009_20161205.txt  /keep

Now, we have to sort files having same starting number for eg. 001 and then we have find latest file based on the date written in file name and delete old files. The same way we have to perform for other files also. So the final output in directory would be following:

001_20161209.txt  /keep
005_20161206.txt  /keep
009_20161205.txt  /keep

This is what I have tried so far:

files=($(find . -name "???_*.txt")) | if ((#files > 1)); then rm -- ${files[1,-2]}; fi

but it is deleting all files except the last one. I want to create a separate group of files having same starting name and then to delete it.

Lucas
  • 2,845

1 Answers1

1

You can reverse the order of the files (sort --reverse) so the latest files will always be the first in a block of files with the same prefix. Then you can keep track of the current block (with $current_prefix) and keep the first file in each block (continue) and rm all the other files in the block:

current_prefix=
find . -name '???_*.txt' | sort --reverse | while read line; do
  if [[ ${line[1,5]} != $current_prefix ]]; then
    # we are at the beginning of a new block
    current_prefix=${line[1,5]}
    continue # actually not needed b/c there is nothing outside the if block.
  else
    rm -- $line
  fi
done

Note: In order to test this first you can preppend all rm commands with echo.

In order to just list the files you want to keep you can use sort and uniq:

find . -name '???_*.txt' | sort --reverse | uniq --check-chars 3
Lucas
  • 2,845
  • Hi, Can we do this using zargs? please guide me. – Deep198 Apr 11 '16 at 17:52
  • @Deep198: What do you have so far with zargs? – Lucas Apr 11 '16 at 21:48
  • @ Lucas : Using autoLoad -U-zargs command how we can achieve above thing, Instead of writing above code is it possible to have any other approach? – Deep198 Apr 12 '16 at 05:39
  • I don't know if there is another way. But what have you tried with zargs until now? Can you post the code that you tried? (I know how to autoload it.) What is the problem with the above answer, why do you need to use zargs? – Lucas Apr 13 '16 at 04:21