0

I have a directory structure like this;

dir
├── dirA
│   └── file1
│   └── subdir
└── dirB
    └── file2
    └── subdir

I need to move file1 to dirA/subdir and file2 to dirB/subdir. How can I do it in Linux?

5 Answers 5

3

From dir you could mv dirA/file1 /dirA/subdir/ and mv dirB/file2 /dirB/subdir/ are you trying to do this in a script or with a single command?

Jason C.

1

This worked for me to move various .yml files in various repo directories into a "tasks" sub directory in each of the repo directories:

for dir in */; do mv -- "$dir"*.yml "${dir}tasks/"; done
1
  • @StephaneChazelas Thanks for the syntax correction, worked before but I agree w/ your correction.
    – netmosis
    May 12, 2022 at 20:56
0

Gnu find

find dir -mindepth 2 -maxdepth 2 -type f -execdir sh -c 'mv -t ./*/ "$1"' find-sh {} \;

find dir \
  -mindepth 2 -maxdepth 2 -type f \
  -execdir sh -c '
        mv -t ./*/ "$1"
  ' find-sh {} \;

original directory structure

dir
├── dirA/
│   ├── fileA
│   └── subdir/
│       ├── e
│       ├── q
│       └── w
└── dirB/
    ├── fileB
    └── subdir/
        ├── c
        ├── x
        └── z

After the move operation

dir
├── dirA/
│   └── subdir/
│       ├── e
│       ├── fileA
│       ├── q
│       └── w
└── dirB/
    └── subdir/
        ├── c
        ├── fileB
        ├── x
        └── z
0

With zsh, you could do:

cd dir || exit
for dir in *(N-/); do
  subdirs=($dir/*(N-/))
  nondirs=($dir/*(N^-/))
  if (( $#subdirs != 1 || $#nondirs == 0 )); then
    print -ru2 Skipping $dir which has $#subdirs subdirs and $#nondirs nondirs.
  else
    mv -- $nondirs $subdirs/
  fi
done

Where we move the non-directory files only if there's only one subdirectory.

Note that with the - glob qualifier, the type of the files is determined after symlink resolution, and that symlinks might become broken after being moved (like if their target starts with nameofsubdir or ..). Hidden files and dirs are ignored.

-2

Do this command in your shell:

mv file1 /dir/dirA
mv file2 /dir/dirB**

mv stands for move

mv "filename.txt" "location/where/you/want/file/to/go"

1
  • Welcome to Stackexchange! Please only post answers that actually address the question. mv file1 /dir/dirA does not move file1 to dirA/subdir. Besides, your answer should not reiterate feedback that has already been given; in this case, you don't add anything to the first answer. Feb 23, 2021 at 0:59

You must log in to answer this question.

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