0

I've been successfully running a script that prints out the names of the files in a specific directory by using

for f in data/* do echo $f

and when I run the program it gives me:

data/data-1.txt data/data-2.txt data/data-3.txt (the files in the data directory)

however, when I need to change all of the file names from data-*.txt to mydata-*txt, I can't figure it out.

I keep trying to use sed s/data/mydata/g $f but it prints out the whole file instead and doesn't change the name correctly. Can anybody give me some tips on how to change the file names? it seems to also change the name of the directory if I use SED, so I'm kind of a dead end. Even using mv doesn't seem to do anything.

  • Maybe this would be helpful: http://stackoverflow.com/questions/8899135/renaming-multiples-files-with-a-bash-loop – rsc Oct 02 '14 at 05:47

1 Answers1

0
for f in data/*
 do
  NewName="$( echo "${f}" | sed 's#/data-\([0-9]*.txt\)$#mydata\1#' )"
  if [ ! "${f}" = "${NewName}" ]
   then
     mv ${f} ${NewName}
   fi 
 done

based on your code but lot of other way to do it (ex: find -exec)

NeronLeVelu
  • 9,908
  • 1
  • 23
  • 43
  • 1
    This will fail if file names contain whitespace or wildcard characters. You should always double-quote file names. `mv "$f" "$NewName"` (the braces are unnecessary). – tripleee Oct 02 '14 at 06:52
  • right, it's just based on sample given where there are no white space in folder and name. To be exact, it also failed if file name content 2 time data- and an digit (also out of scope). Once again your are right, "un"brace is optional and i take the habit to always use brace with huge script. you got your point ;-) – NeronLeVelu Oct 02 '14 at 07:44