1

It won't look like it, but I've spent 3+ hours trying to figure this out... I am trying to identify files in all subdirectories of a parent directory with particular attributes (name and size) then rename the files to their subdirectory name and copy them to the parent directory. My closest attempt (I think) has been:

find /data/data2/parent/ -size 25166176c -name "o*.nii" -exec cp {} $subdir/o*.nii $subdir.nii \;

To this, I get two lines of: "cp: target '/data/data2/parent/3145_V2.nii' is not a directory" I checked to make sure there is only one file that would meet both attributes, and there is. Also noteworthy, there are two subdirectories under "parent/" with a relevant file that should be picked up by the find command but it only printed the error regarding one of the two, "parent/3145_v2" (and appeared to ignore the other subdirectory).

  • 2
    Pls try to narrow down the error: Does find find the correct files, and no more? Does the cp / mv command work on its own? A "rename" would be done by mv, not cp. And, is it correct that the file should be renamed AND copied? On top, find might not be able to extract the subdir name, so that would have to be done elsewhere. – RudiC Aug 27 '18 at 18:03
0

I have a rule I like to follow--if I spend more than 30 minutes working on constructing a single command in bash, I switch over to python 3.

This problem could be easily solved in python:

#/usr/local/bin/python3

import os, re

DIR_TO_SEARCH = os.getcwd()   #change this to what you want

for (dirpath, dirnames, filenames) in os.walk(DIR_TO_SEARCH):
    if dirpath == DIR_TO_SEARCH:
        # you said you just want subdirectories, so skip this
        continue
    else:
        for name in filenames:
            full_path = dirpath + '/' + name
            #check for the attributes you're looking for. Change this to your needs.
            if re.search(r'o*\.nii', name) or os.path.getsize(full_path) > 0:
                #rename the file to its directory's name, and move it to the parent dir
                print('Moving {} to {}'.format(full_path, dirpath + '.nii'))
                os.rename(full_path, dirpath + '.nii')  

In general, python may be less plug-n-play than bash tools, but it has the advantage of being very well-documented and pretty free from bugs. Just my two cents.

Feel free to use the script above, I tested it and it works fine. Cheers :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.