Tell me more ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

How can I bulk replace the prefix for many files?

I have a lot of files like

  • TestSRConnectionContext.h
  • TestSRConnectionContext.m

I would like to change all them to

  • CLConnectionContext.h
  • CLConnectionContext.m

How would I do this?

share|improve this question

7 Answers

up vote 1 down vote accepted
for name in TestSR*
do
    newname=CL"$(echo "$name" | cut -b7-)"
    mv "$name" "$newname"
done
share|improve this answer
Thx, i got this right now by myself too. Marking as answer. Thx – ErikTJ Sep 6 '12 at 16:35

Shell parameter expansion is enough for simple transformations like this. Command substitution is less efficient because of the need to spawn extra processes (for the command substitution itself and the cut/sed).

for f in TestSR*; do mv "$f" "CL${f#TestSR}"; done
share|improve this answer

I'd say the simplest it to just use the rename command. See it's man page (it's as simple as it gets) but for changing extensions the following should work just fine:

rename 's/^TestSR/CL/' *

This of course expects you to be on the directory of the files. This will not overwrite files. If you want that, just pass the -f option.

EDIT: see jw013 comment below about multiple versions of rename

share|improve this answer
1  
A caveat: multiple versions of rename exist in the wild. Check your local rename documentation to figure out how to use yours. – jw013 Sep 6 '12 at 17:39

Well, it wasn't as hard as i though.

$ for f in TestSR*.m; do mv $f CL$(echo $f | cut -c7-); done;
$ for f in TestSR*.h; do mv $f CL$(echo $f | cut -c7-); done;
share|improve this answer
1  
In case it helps for the future, you don't have to repeat the commands for your two patterns; you can use (for example): for f in TestSR*.[mh], for f in TestSR*.{m,h}, for f in TestSR*.m TestSR*.h. – mrb Sep 6 '12 at 22:37

If you need something more perlish you can do this

perl -e 'for(@ARGV) { rename($_, $n) if( ($n = $_ ) =~ s/^TestSR/CL/) }' *
share|improve this answer

Here's one way:

ls *.{h,m} | while read a; do n=CL$(echo $a | sed -e 's/^Test//'); mv $a $n; done
  • ls *.{h,m} --> Find all files with .h or .m extension
  • n=CL --> Add a CL prefix to the file name
  • sed -e 's/^Test//' --> Removes the Test prefix from the file name
  • mv $a $n --> Performs the rename
share|improve this answer

You can try with:

for i in TestSR*; do mv ${i} ${i/#TestSR/CL}; done

See man bash (section "Parameter Expansion") for details.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.