Unix- Copying the same file from multiple directories into a new directory while renaming the files Unix- Copying the same file from multiple directories into a new directory while renaming the files unix unix

Unix- Copying the same file from multiple directories into a new directory while renaming the files


Something along this line should work:

for f in [0-9][0-9]/log.lammps; do  d=$(dirname ${f})  b=$(basename ${f})  cp ${f} logs/${b}.${d}done


That's easy-peasy with the magic of shell scripting. I'm assuming you have bash available. Create a new file in the directory that contains these subdirectories; name it something like copy_logs.sh. Copy-paste the following text into it:

#!/bin/bash# copy_logs.sh# Copies all files named log.lammps from all subdirectories of this# directory, except logs/, into subdirectory logs/, while appending the name# of the originating directory.  For example, if this directory includes# subdirectories 1/, 2/, foo/, and logs/, and each of those directories# (except for logs/) contains a file named log.lammps, then after the# execution of this script, the new file log.lammps.1, log.lammps.2, and# log.lammps.foo will have been added to logs/.  NOTE: any existing files# with those names in will be overwritten.DIRNAMES=$( find . -type d | grep -v logs | sed 's/\.//g' | sed 's/\///g' | sort )for dirname in $( echo $DIRNAMES )do    cp -f $dirname/foo.txt logs/foo$dirname    echo "Copied file $dirname/foo.txt to logs/foo.$dirname"done

See the script's comments for what it does. After you've saved the file, you need to make it executable by commanding chmod a+x copy_logs.sh on the command line. After this, you can execute it by typing ./copy_logs.sh on the command line while your working directory is the directory that contains the script and the subdirectories. If you add that directory to your $PATH variable, you can command copy_logs.sh no matter what your working directory is.

(I tested the script with GNU bash v4.2.24, so it should work.)

For more on bash shell scripting, see any number of books or internet sites; you might start with the Advanced Bash-Scripting Guide.