Multiple File Rename based on pattern - one line

All,

I wanted to copy the files

From:

Daily_XYZ_TEST_1.csv
Daily_XYZ_TEST_2.csv
Daily_XYZ_TEST_3.csv
Daily_XYZ_TEST_4.csv

To:

Daily_ABC_TEST_1.csv
Daily_ABC_TEST_2.csv
Daily_ABC_TEST_3.csv
Daily_ABC_TEST_4.csv

I have tried the rename command but it is not working
rename 's/*XYZ*/*ABC*/' *.csv

Any advice welcome

First, there is no utility named rename that is callable from the shell on most systems. If you're talking about the perl rename function, it would be a good idea to state that you're having a problem with perl rather than making us guess.

Assuming this is a statement in a perl script, I think you want to change:

rename 's/*XYZ*/*ABC*/' *.csv

to:

rename 's/_XYZ_/_ABC_/' *.csv

PS Note that rename does not copy files, it renames (or moves) them.

1 Like

Thank you for the reply. Unfortunately I was looking up some results on google and did not check that rename is only available in perl.

I would like to see if there was a one line command that i could use in the shell to perform my pattern based rename.

ahem: what you did was throwing a "sed"-command at the shell. Big surprise, being not "sed" the shell was confused. Talk japanese to any average middle-european and you are bound to get the same reaction. ;-))

What you have to do is: set up a loop, looping through the filenames and storing these in a shell variable. Then change the contents of the shell variable to reflect the new name for the respective file. Finally, using the old and the new value of the variable, use the source- and target-names in a "mv" command to rename the files:

ls Daily_XYZ_TEST_*.csv | while read SRCFILE ; do
     IDX=${SRCFILE#Daily_XYZ_TEST_}   # cut off "Daily_XYZ_TEST_" from front
     IDX=${IDX%.csv}                  # cut off ".csv" from end
     mv "$SRCFILE" "Daily_ABC_TEST_${IDX}.csv"
done

I hope this helps.

bakunin

1 Like

If you're using a recent bash or a ksh newer than its 1988 version as your shell, you could also use:

for i in Daily_XYZ_TEST_*.csv
do      mv "$i" "${i/_XYZ_/_ABC_}"
done
1 Like

Twenty years ago I met "mmv.c", "multi-move".
The compiled "mmv" needed in the substitution =1 =2 for each corresponding wild card * or ?
In your case

mmv "*XYZ*.csv" "=1ABC=2.csv"