Search code examples
linuxshellbatch-processingfile-renamebatch-rename

How to rename files in linux shell using regexp?


I have some files:

/var/www/media/0001/0001_123456_12.jpg
/var/www/media/0002/0002_123456_12.jpg
/var/www/media/0003/0003_123456_12.jpg

and I want to rename them to:

/var/www/media/0001/0001_test.jpg
/var/www/media/0002/0002_test.jpg
/var/www/media/0003/0003_test.jpg

My idea was to find the first _, remove the rest of the file until the . then add test.

Any ideas?


Solution

  • find /var/www/media/ -name \*.jpg -exec sh -c '
      a=$(echo {} | sed s/_123456_/_/);
      [ "$a" != "{}" ] && mv "{}" "$a" '
    

    You find all jpg files in the /var/www/media and run for each file the command:

    a=$(echo {} | sed s/_123456_/_/)
    [ "$a" != "{}" ] && mv "{}" "$a"
    

    After this command, the a variable has rewritten name of the file inside:

    a=$(echo {} | sed s/_123456_/_/)
    

    The we compare the a variable and the realname ({}), and they are not equal the file must be renamed.