How to rename with prefix/suffix?

前端 未结 9 1478
独厮守ぢ
独厮守ぢ 2020-11-27 10:52

How do I do mv original.filename new.original.filename without retyping the original filename?

I would imagine being able to do something like mv

相关标签:
9条回答
  • 2020-11-27 11:25

    Bulk rename files bash script

    #!/bin/bash
    # USAGE: cd FILESDIRECTORY; RENAMERFILEPATH/MultipleFileRenamer.sh FILENAMEPREFIX INITNUMBER
    # USAGE EXAMPLE: cd PHOTOS; /home/Desktop/MultipleFileRenamer.sh 2016_
    # VERSION: 2016.03.05.
    # COPYRIGHT: Harkály Gergő | mangoRDI (https://wwww.mangordi.com/) 
    
    # check isset INITNUMBER argument, if not, set 1 | INITNUMBER is the first number after renaming
    if [ -z "$2" ]
        then i=1;
    else
        i=$2;
    fi
    
    # counts the files to set leading zeros before number | max 1000 files
    count=$(ls -l * | wc -l)
    if [ $count -lt 10 ]
        then zeros=1;
    else
        if [ $count -lt 100 ]
            then zeros=2;
        else
            zeros=3
        fi
    fi
    
    # rename script
    for file in *
    do
        mv $file $1_$(printf %0"$zeros"d.%s ${i%.*} ${file##*.})
        let i="$i+1"
    done
    
    0 讨论(0)
  • 2020-11-27 11:28

    In my case I have a group of files which needs to be renamed before I can work with them. Each file has its own role in group and has its own pattern.

    As result I have a list of rename commands like this:

    f=`ls *canctn[0-9]*`   ;  mv $f  CNLC.$f
    f=`ls *acustb[0-9]*`   ;  mv $f  CATB.$f
    f=`ls *accusgtb[0-9]*` ;  mv $f  CATB.$f
    f=`ls *acus[0-9]*`     ;  mv $f  CAUS.$f
    

    Try this also :

    f=MyFileName; mv $f {pref1,pref2}$f{suf1,suf2}
    

    This will produce all combinations with prefixes and suffixes:

    pref1.MyFileName.suf1
    ...
    pref2.MyFileName.suf2
    

    Another way to solve same problem is to create mapping array and add corespondent prefix for each file type as shown below:

    #!/bin/bash
    unset masks
    typeset -A masks
    masks[ip[0-9]]=ip
    masks[iaf_usg[0-9]]=ip_usg
    masks[ipusg[0-9]]=ip_usg
    ...
    for fileMask in ${!masks[*]}; 
    do  
    registryEntry="${masks[$fileMask]}";
    fileName=*${fileMask}*
    [ -e ${fileName} ] &&  mv ${fileName} ${registryEntry}.${fileName}  
    done
    
    0 讨论(0)
  • 2020-11-27 11:29

    You could use the rename(1) command:

    rename 's/(.*)$/new.$1/' original.filename
    

    Edit: If rename isn't available and you have to rename more than one file, shell scripting can really be short and simple for this. For example, to rename all *.jpg to prefix_*.jpg in the current directory:

    for filename in *.jpg; do mv "$filename" "prefix_$filename"; done;
    
    0 讨论(0)
提交回复
热议问题