views:

172

answers:

6

Hello,

sorry for the properly stupid question, but I am quite a newbie. 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? I tried several things from this forum but I seem to make a mistake. Thanks for your help!

+1  A: 

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'

Stephen lacy
+2  A: 

I like to do this with sed. In you case:

for x in DET01-*.dat; do
    echo $x | sed -r 's/DET01-ABC-(.+)\.dat/mv -v "\0" "DET01-XYZ-\1.dat"/'
done | sh -e

It is best to omit the "sh -e" part first to see what will be executed.

stribika
maybe I am doing something wrong, but this is doing nothing to my files?
not_a_geek
Are you trying with or without the "sh -e"? If you are trying without it is not supposed to. It just prints what will be executed ("mv -v ... ..." lines) as a chance to check if everything is ok. If you like what you see add the "sh -e".
stribika
+7  A: 

There are a couple of variants of a rename command, in your case, it may be as simple as

rename ABC XYZ *.dat

You may have a version which takes a Perl regex;

rename 's/ABC/XYZ/' *.dat
Paul Dixon
+1 the simplest way
rangalo
thanks a million! That was easy (if you know how to ;-) )
not_a_geek
Welcome to stackoverflow!
Paul Dixon
I don't rename is available in all Unix variants. Sed is a good fall back.
Jim
+2  A: 

Something like this will do it. The for loop may need to be modified depending on which filenames you wish to capture.

for fspec1 in DET01-ABC-5_50-*.dat ; do
    fspec2=$(echo ${fspec1} | sed 's/-ABC-/-XYZ-/')
    mv ${fspec1} ${fspec2}
done

You should always test these scripts on copies of your data, by the way, and in totally different directories.

paxdiablo
A: 

thanks everybody! I will look into your hints for sure, Stephen lacy

not_a_geek
A: 

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.

Sam Bisbee