1

I have the following commands that I would like to run inside each subdirectory of the current working directory. Here are the commands:

OUTPUTFN=`basename $PWD`
cat *.xml > $OUTPUTFN.txt
mv $OUTPUTFN.txt $OUTPUTFN.xml
mv $OUTPUTFN.xml ..

There are over 700 folders in this directory, I want it to go into each, execute those four commands, and then go to the next, execute the commands, and repeat. I've tried combining several samples from this site with my commands but can't get it to work.

1
  • All directories are listed inside the same directory. There is a maximum of one level.
    – jlacroix82
    Jun 28, 2012 at 16:23

1 Answer 1

3

Script

for DIR in *; do
    [ -d "$DIR" ] && cat "$DIR"/*.xml > "$DIR.xml"
done

One-liner

for DIR in *; do [ -d "$DIR" ] && cat "$DIR"/*.xml > "$DIR.xml"; done

How it works

  • Bash expands * to all files and directories in the current directory.

  • for DIR in *; do ... done goes through these and executes ... for each one.

    In each case, $DIR holds the name of the current entry.

  • [ -d "$DIR" ] && ... checks if $DIR is indeed a directory (and not a file).

    If it is, ... gets executed.

  • cat "$DIR"/*.xml > "$DIR.xml" does precisely what your four lines of code do.

2
  • I'm testing it now. One question about this line: cat "$DIR"/*.xml > "$DIR.xml" Since $DIR.xml" is itself an XML file, would it cat itself back into $DIR.xml again since the output file qualifies as the very thing it's merging?
    – jlacroix82
    Jun 28, 2012 at 16:50
  • This isn't an issue since cat operates on all .xml files in $DIR, while $DIR.xml is located in the parted folder.
    – Dennis
    Jun 28, 2012 at 16:56

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .