3

I working with linux, bash.

I have one directory with 100 folders in it, each one named different.

In each of these 100 folders, there is a file called first.bars (so I have 100 files named first.bars). Although all named first.bars, the files are actually slightly different.

I want to get all these files moved to one new folder and rename/number these files so that I know which file comes from which folder. So the first first.bars file must be renamed to 001.bars, the second to 002.bars.. etc.

I have tried the following:

ls -d * >> /home/directorywiththe100folders/list.txt
cat list.txt | while read line;
do cd $line;
mv first.bars /home/newfolder

This does not work because I can't have 100 files, named the same, in one folder. So I only need to know how to rename them. The renaming must be connected to the cat list.txt, because the first line is the folder containing the first file wich is moved and renamed. That file will be called 001.bars.

Chris Seymour
  • 83,387
  • 30
  • 160
  • 202
rubano
  • 31
  • 2

2 Answers2

5

Try doing this :

$ rename 's/^.*?\./sprintf("%03d.", $c++)/e' *.bar

If you want more information about this command, see this recent response I gave earlier : How do I rename multiple files beginning with a Unix timestamp - imapsync issue

Community
  • 1
  • 1
Gilles Quénot
  • 173,512
  • 41
  • 224
  • 223
  • I can't get this to work. I first tried it incorporating it in my own code, but that doesn't work. Then I tried it in a single folder (one of those 100) and tried to rename the first.bar file with your code. Unfortunately, nothing happens. Rename asks me to give 3 inputs: from, to and file. *.bar is obviously the file, but I think he doesn't recognize the from and to. – rubano Mar 18 '13 at 17:24
  • @rubano : I over guess that **you don't have read my link** ! Especially the **note** part. – Gilles Quénot Mar 18 '13 at 22:32
  • I actually read your link, but it didn't help (at first). But I eventually did get it to work. Thank you very much Sputnick! – rubano Mar 26 '13 at 11:46
0

If the rename command is not available,

for d in /home/directorywiththe100folders/*/; do
    newfile=$(printf "/home/newfolder/%d.bars" $(( c++ )) )
    mv "$d/first.bars" "$newfile"
done
chepner
  • 497,756
  • 71
  • 530
  • 681