0

I am new to unix (using the Mac OS X terminal) and am trying to rename certain files by adding some text in the middle of the filename. For all files in the folder ./temp I would like to replace filenames beginning dr_ic0004 with dr_ic0004_DMN.

For example dr_0004_tstat1.txt and dr_0004_tstat2.txt with dr_0004_DMN_tstat1.txt and dr_0004_DMN_tstat2.txt respectively.

  • possible duplicate of [Rename multiple files in Unix](http://stackoverflow.com/questions/1086502/rename-multiple-files-in-unix) –  Jun 29 '12 at 13:48
  • You'll need a for to capture the names, then you'll need to process the name with sed or gawk or something to create the new name. Type man sed to look up it's syntax. – Spidey Jun 29 '12 at 13:50
  • 1
    Welcome to StackOverflow! We'd love to help. What have you tried? – ghoti Jun 29 '12 at 13:52
  • 1
    Thanks for all your help. This worked: for i in dr_ 0004*; do mv $i $(echo $i | sed 's/^dr_0004/dr_ 0004_DMN/'); done – user1491292 Jun 29 '12 at 14:20
  • http://theunixshell.blogspot.com/2013/01/bulk-renaming-of-files-in-unix.html – Vijay Mar 26 '13 at 12:38

2 Answers2

2
for filename in dr_0004*
do
    mv "$filename" dr_0004_DMN"${filename#dr_0004}"
done
Jo So
  • 25,005
  • 6
  • 42
  • 59
-1

Suppose you had dr_ic0004foo, dr_ic0004bar and dr_ic0004baz. To see them all, you'd do:

ls dr_ic0004*

To isolate the variable parts (foo, bar and baz) you could run that list through sed:

ls dr_ic0004*|sed 's/^dr_ic0004//'

To rename a single file you would use mv:

mv dr_ic0004foo dr_ic0004_DMNfoo

And to iterate over a list, you could use a for loop:

for x in foo bar baz; do echo $x ; done

Put them all together and you get:

for x in `ls dr_ic0004*|sed 's/^dr_ic0004//'`; do mv dr_ic0004$x dr_ic0004_DMN$x; done
Beta
  • 96,650
  • 16
  • 149
  • 150