Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Copy and Rename Multiple Files with Regular Expressions in bash

I've got a file structure that looks like:

A/
    2098765.1ext
    2098765.2ext
    2098765.3ext
    2098765.4ext
      12345.1ext
      12345.2ext
      12345.3ext
      12345.4ext

B/
    2056789.1ext
    2056789.2ext
    2056789.3ext
    2056789.4ext
      54321.1ext
      54321.2ext
      54321.3ext
      54321.4ext

I need to rename all the files that begin with 20 to start with 10; i.e., I need to rename B/2022222.1ext to B/1022222.1ext

I've seen many of the other questions regarding renaming multiple files, but couldn't seem to make it work for my case. Just to see if I can figure out what I'm doing before I actually try to do the copy/renaming I've done:

for file in "*/20?????.*"; do
    echo "{$file/20/10}";
done

but all I get is

{*/20?????.*/20/10}

Can someone show me how to do this?

like image 270
jlconlin Avatar asked Feb 13 '13 17:02

jlconlin


2 Answers

You just have a little bit of incorrect syntax is all:

for file in */20?????.*; do mv $file ${file/20/10}; done
  1. Remove quotes from the argument to in. Otherwise, the filename expansion does not occur.
  2. The $ in the substitution should go before the bracket
like image 190
Explosion Pills Avatar answered Oct 19 '22 18:10

Explosion Pills


Here is a solution which use the find command:

find . -name '20*' | while read oldname; do echo mv "$oldname" "${oldname/20/10}"; done

This command does not actually do your bidding, it only prints out what should be done. Review the output and if you are happy, remove the echo command and run it for real.

like image 42
Hai Vu Avatar answered Oct 19 '22 17:10

Hai Vu