简体   繁体   中英

Move multiple files to directories in linux

I have a directory structure like this;

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

I need to move file1 to subdir1 and file2 to subdir2. How can I do it in Linux?

I solved my problem with this;

$ for dir in dir/*/; do mv dir/*/file* "$dir/subdir"; done

You can write a simple bash script. below is the sample directory tree structure.

tree 
.
|-- dir-2
|   |-- file-1
|   |-- file2
|   |-- file3
|   |-- file4
|   `-- subdir
|-- dir-3
|   |-- file-1
|   |-- file2
|   |-- file3
|   |-- file4
|   `-- subdir
|-- dir-4
|   |-- file-1
|   |-- file2
|   |-- file3
|   |-- file4
|   `-- subdir

run the below script from the parent directory.

#!/bin/bash
ls -d */ > out.txt
for i in `cat out.txt` ; do

ls -l $i
cd $i
mv * subdir/ 
cd .. 
   
done;

tree structure after executing the above script.

$ tree 
.
|-- dir-2
|   `-- subdir
|       |-- file-1
|       |-- file2
|       |-- file3
|       `-- file4
|-- dir-3
|   `-- subdir
|       |-- file-1
|       |-- file2
|       |-- file3
|       `-- file4
|-- dir-4
|   `-- subdir
|       |-- file-1
|       |-- file2
|       |-- file3
|       `-- file4

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM