Search code examples
macosunixshellsedln

shell script to link specific files up one level


I've got a folder that's got a whole lot of folders inside, which each contain a movie file. Now I want to be able to see all these movies at one time (but I have to preserve the folder structure) so I wanted to symlink them all to the top level folder (flat view in Directory Opus would be the go here, but I'm on a mac). Here's my attempt

for file in */*/*.mov; 
do 
newname='echo $file | sed "s|[^/]*/[^/]*/||g"';
ln -s $file echo $newname;
done

So what I'm trying to do on line 3 is turn the path foo/bar/spud.mov into spud.mov and then on line 4 do ln -s foo/bar/spud.mov spud.mov

But it doesn't work, all I get is

ln: "s|[^/]/[^/]/||g": No such file or directory

I've tried various combinations of quotes and escapes, but with no luck. The sed expression works, but I've obviously mucked up something with my variables.

Thanks


Solution

  • What's with all the echo $file | sed or awk stuff, anyways? basename's made for this purpose.

    for file in */*/*.mov; do 
      newname=`basename $file1
      ln -s $file $newname;
    done
    

    But, really, ln does the same thing when given a directory, so:

    for file in */*/*.mov; do
      ln -s "$file" .
    done
    

    Or a really general purpose version that's smart enough to only call ln as many times as needed:

    find . -name \*.mov -depth +1 -print0 | xargs -0 -J % ln -s % .
    

    That is, in the local directory, find everything with a name ending in .mov that's not in the current directory (depth is more than 1), separate the output with NULLs, and pipe into xargs, which is looking for NULL-separate input, and will pass . as the argument to ln after all the arguments it read on stdin.