2

I have a directory of files with filenames of the form <num1>v<num2>.txt. I'd like to find all files for which <num1> is a duplicate. When duplicates are found, we should delete the ones with smaller <num2>.

Is this possible? I could easily write a python script to handle this, but thought it might be a nice application of built-in zsh features.

Example

In the following list of files, the first three have duplicate <num1> parts. As well, the fourth and fifth are duplicate.

012345v1.txt
012345v2.txt
012345v3.txt
3333v4.txt
3333v7.txt
11111v11.txt

I would like to end up with directory containing

012345v3.txt
3333v7.txt
11111v11.txt
4

You could do something like:

files=(<->v<->.txt(n))
typeset -A h
for f ($files) h[${f%%v*}]=$f
keep=($h)
echo rm ${files:|keep}

(remove echo if happy)

  • <->: any sequence of digits (<x-y> glob operator with no bound specified)
  • (n): numeric sort
  • ${f%%v*}: standard/ksh greedy pattern stripping from the end.
  • ${files:|keep}: array disjunction.
0

I'm not familiar too much with zsh shell, and I'm coming with below awk command combination with find and sort which make sorting the files found first with natural sort of (version) numbers within text from man sort says.

Then passing awk with defining -F'v' and add to an array based on first duplicated part of file name (this ensure that last one is keeping in array), so the command I'm talking would be as follows to result the files with big v number:

awk -F'v' '{U[$1]=$1"v"$2}END{for(x in U)print U[x]}' <(find . -type f|sort -V)
./012345v3.txt
./3333v7.txt
./11111v11.txt

Now you got the list of files which you should keep and delete rest.

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.