Alex Rivera | Logout

Renaming part of a filename

Asked 2009-09-08T08:45:20.020
117

I have loads of files which look like this:

DET01-ABC-5_50-001.dat
...
DET01-ABC-5_50-0025.dat

and I want them to look like this:

DET01-XYZ-5_50-001.dat
...
DET01-XYZ-5_50-0025.dat

How can I do this?

Edit
Report

2 Answers

4

You'll need to learn how to use sed http://unixhelp.ed.ac.uk/CGI/man-cgi?sed

And also to use for so you can loop through your file entries http://www.cyberciti.biz/faq/bash-for-loop/

Your command will look something like this, I don't have a term beside me so I can't check

for i in `dir` do mv $i `echo $i | sed '/orig/new/g'`
answered 2009-09-08T08:47:50.693
2

All of these answers are simple and good. However, I always like to add an interactive mode to these scripts so that I can find false positives.

if [[ -n $inInteractiveMode ]]
then
    echo -e -n "$oldFileName => $newFileName\nDo you want to do this change? [Y/n]: "
    read run

    [[ -z $run || "$run" == "y" || "$run" == "Y" ]] && mv "$oldFileName" "$newFileName"
fi

Or make interactive mode the default and add a force flag (-f | --force) for automated scripts or if you're feeling daring. And this doesn't slow you down too much: the default response is "yes, I do want to rename" so you can just hit the enter key at each prompt (because of the -z $run test.

answered 2009-09-09T05:15:23.887

Your Answer