简体   繁体   中英

Create subfolder with same name as parent and move files into it

I have folders as below. I want to create subdirectory with same name and move only few of the files into sub directory

Input

 Parent

   folder1/a.txt
   folder1/b.txt
   folder2/a.txt
   folder2/b.txt
   folder3/a.txt
   folder3/b.txt 


Output

  Parent

  folder1/folder1/a.txt
  folder1/b.txt
  folder2/folder2/a.txt
  folder2/b.txt
  folder3/folder3/a.txt
  folder3/b.txt 

I tried this , but this is working only for files not folders

       for file in *; do dir=$(echo $file | cut -d. -f1); mkdir -p $dir; mv $file $dir; done

If your shell is bash, you can run the following:

for file in */a.txt ; do 
    dir=${file%/a.txt}
    mkdir "$dir/$dir"
    mv "$file" "$dir/$dir"
done

It uses the parameter expansion to remove the /a.txt from the file name which only leaves the directory name in $dir .

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