0

I have a directory with lots of sub-directories. The sub-directories each have unique names.

I would like to take every file ending with '.nc' in the sub-directories and move those files up one level.

Is there a way to do this in the terminal?

3
  • 3
    Can we assume that the filenames are distinct from their containing directory, so that there's no collision? e.g. a file named subdir1.nc does not exist in a directory named subdir1.nc? And with these files in various subdirectories, do you want them moved one level up from where they are, or up one level from where you are, at the top somewhere?
    – Jeff Schaller
    Apr 21, 2020 at 14:44
  • I would write a recursive directory walker where if I run into a .nc match I move it to .., and if I find a directory, I just call the function with the new directory and it does the same thing all over again until it removes everything off the stack.
    – NiteRain
    Apr 21, 2020 at 15:17
  • The filenames and the directories all have distinct, unique names. Apr 21, 2020 at 15:26

1 Answer 1

1

Using GNU find:

Move each *.nc file up one level from where they are:

find . -type f -name '*.nc' -execdir mv -i {} .. \;

Move each *.nc file up one level from where you are (to the parent directory of your current dir):

find . -type f -name '*.nc' -exec mv -i {} .. \;
5
  • Perfect. Thank you very much. Apr 21, 2020 at 15:39
  • @Freddy, simply elegant. Definitely going to use this in the future. Faster, than writing a small bash script for sure.
    – NiteRain
    Apr 21, 2020 at 15:53
  • If you add the -n to the move it won't move files with same name in the directory you are moving to.
    – NiteRain
    Apr 21, 2020 at 15:57
  • @Freddy question what is the \; for?
    – NiteRain
    Apr 21, 2020 at 15:59
  • @NiteRain The syntax for actions on single files is -exec command ;, the ; is escaped with a \ to prevent interpretation by the shell and could also be quoted. See man find.
    – Freddy
    Apr 21, 2020 at 16:14

You must log in to answer this question.

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