How to rename files in bash to increase number in name?

后端 未结 4 1206
鱼传尺愫
鱼传尺愫 2021-01-07 02:20

I have a few thousand files named as follows:

Cyprinus_carpio_600_nanopore_trim_reads.fasta                
Cyprinus_carpio_700_nanopore_trim_reads.fasta             


        
4条回答
  •  遥遥无期
    2021-01-07 02:51

    Considering the filename conflicts in the increasing order, I first thought of reversing the order but there still remains the possibility of conflicts in the alphabetical (standard) sort due to the difference to the numerical sort.
    Then how about a two-step solution: in the 1st step, an escape character (or whatever character which does not appear in the filename) is inserted in the filename and it is removed in the 2nd step.

    #!/bin/bash
    
    esc=$'\033' # ESC character
    
    # 1st pass: increase the number by 100 and insert a ESC before it
    for f in *.fasta; do
        num=${f//[^0-9]/}
        num2=$((num + 100))
        f2=${f/$num/$esc$num2}
        mv "$f" "$f2"
    done
    
    # 2nd pass: remove the ESC from the filename
    for f in *.fasta; do
        f2=${f/$esc/}
        mv "$f" "$f2"
    done
    

提交回复
热议问题