Advertisement

Unix Shell Scripting Question

Started by December 21, 2004 03:18 AM
3 comments, last by Kylotan 20 years, 2 months ago
Hi All our game build-related scripts are written using unix shell scripts and then executed using bash. I'm a little new to unix shells, so I was wandering if somebody could help me out with the following problem: I've got a directory structure something like so:

Dir1
 File1
 File2
 File3
Dir2
 File4
 File5
 Dir3
  File6
  File7


And I would like to write a script that will copy all the files to a single directory and name the files based on their original path. So I'd have:

NewDir
 Dir1_File1
 Dir1_File2
 Dir1_File3
 Dir2_File4
 Dir2_File5
 Dir2_Dir3_File6
 Dir2_Dir3_File7


I know how to do this using VB scripts, but how can I do it using a Unix shell?
This should work (on bash at least).

Usage: ./flatten.sh newdir
If newdir doesn't exist, it is created.

#!/bin/bash# check if the user gave the newdir nameif [[ $1 ]]; then    # create newdir if it doesn't already exist    mkdir -p $1    # for each file in current directory and its subdirs    for i in `find`; do        # if it is a regular file        if [[ -f $i ]]; then            # transform the filename and copy the file            cp $i $1/`echo $i|sed -e 's/\.\///;s/\//_/g'`;         fi;     done;else    # Print help if no parameter given    echo "Usage: ./flatten.sh newdir"fi
Advertisement
I feel compelled to tell you that it's so much easier in Python using os.path.walk() or os.walk()...
Ok, challence accepted :)

Here's what I came up with (with my admittedly non-substantial python skills). The two versions are very similar: the main difference is python's wordier syntax. The shell language, being more special, has some handy (though arguably somewhat obscure) syntactic shortcuts.

But as I said, I haven't coded much in python, so if I missed something essential and the python version can be compacted substantially, I'd like to know.

#!/usr/bin/pythonimport osimport sysimport shutilif len(sys.argv) == 2:  # create newdir if it doesn't exist  if not os.path.exists(sys.argv[1]):     os.mkdir(sys.argv[1])  # for each file  for root,dirs,files in os.walk("."):    for name in files:      fullname = os.path.join(root, name)      # transform name, copy file      if not os.path.isdir(fullname):        shutil.copy(fullname, os.path.join(sys.argv[1], fullname.lstrip('./').replace('/', '_')))else:  # print help if no arguments given  print 'Usage: flatten.py newdir'
I'd be tempted to use list comprehensions like so:

filenames = []
for (direc, subdirs, fnames) in os.walk("c:\your\directory\here"):
filenames .extend([os.path.join(direc, fname) for fname in fnames])

But I doubt it'll get much more than a line or two shorter.

This topic is closed to new replies.

Advertisement