Search code examples
mv

Rename a specific part of filename


Ciao,

i need rename the file created in one path with this syntax

20230103143408_device_activation.csv

in

20230103143408_attivazioniDevice.csv

This part will be replace _device_activation.csv into _attivazioniDevice.csv

How can i proceed?

mmv '*device_activation.csv' 'attivazioniDevice.csv'


Solution

  • There are many ways to achieve this, but a simple one that springs to mind is using find, cut and xargs like this...

    find -type f -name '*device_activation.csv' | cut -d'_' -f1 | xargs -I % sh -c "mv %_device_activation.csv %_attivazioniDevice.csv"
    

    Example usage...

    ls -l
    -rw-r--r--. 1 kcc users 0 Jan  3 15:39 20230103143407_device_activation.csv
    -rw-r--r--. 1 kcc users 0 Jan  3 15:34 20230103143408_device_activation.csv
    -rw-r--r--. 1 kcc users 0 Jan  3 15:39 20230103143409_device_activation.csv
    
    find -type f -name '*device_activation.csv' | cut -d'_' -f1 | xargs -I % sh -c "mv %_device_activation.csv %_attivazioniDevice.csv"
    
    ls -l
    -rw-r--r--. 1 kcc users 0 Jan  3 15:39 20230103143407_attivazioniDevice.csv
    -rw-r--r--. 1 kcc users 0 Jan  3 15:34 20230103143408_attivazioniDevice.csv
    -rw-r--r--. 1 kcc users 0 Jan  3 15:39 20230103143409_attivazioniDevice.csv