1

So I've got a folder with 2n files. n them are .foo files, n of them .bar files. I want to copy the filenames of the .foo files (which are all different) to the .bar files ordered alphabetically. The extension must remain as they are.

Joren
  • 5,053
  • 8
  • 38
  • 54
  • This is pretty unclear to me. Can you give a small example? You might have 2n, i.e. 22 files, a.foo, b.foo and a.bar, b.bar? Will there always be pairs, if so? Then you want to copy a.foo to a.bar? No - that doesnt make sense. You have a.foo, b.foo and p.bar, q.bar and you want the first (a.foo) to spent the name for p.bar which shall be renamed to a.bar (extension remains). Then b.foo to q.bar? But the content of p.bar, q.bar isn't touched - they are just renamed? – user unknown Aug 25 '13 at 02:47

1 Answers1

0

Let's say you've got (a,b,c).foo and (p,q,r).bar:

ls
a.foo  b.foo  c.foo  p.bar  q.bar  r.bar

You collect the foos and bars in array variables:

foos=(*.foo)
bars=(*.bar)

The size of an array is ${#foos[*]}, the indexes go from 0 to len-1. The first element is ${foos[0]} or ${bars[0]}.

for f in $(seq 0 $((${#foos[*]}-1))) 
do
  fool=${foos[$f]}; 
  echo mv ${bars[$f]} ${fool%.foo%.bar}
  mv ${bars[$f]} ${fool/.foo/.bar}
done 

mv p.bar a.bar
mv q.bar b.bar
mv r.bar c.bar

If you don't like the echo, remove it. The script assumes a matching number of foo and bar files. I'm not sure wether line 3 and 4 will always list the names in alphabetical order - it did in my tests but I don't have a written specification for that.

If the file contains an additional ".foo", like "a.foo-bork.foo" it will not work as intendet and it isn't sanitized against blanks in filenames or linebreakes and the like. But it might do what you want.

user unknown
  • 6,507