Move a group of files to a new folder if their file names, minus extension, matches?

僤鯓⒐⒋嵵緔 提交于 2019-12-04 21:22:41

Think you want something like this.

#!/bin/bash

dir="/somedir/"
for i in "$dir"*; do
  if [ -f "$i" ]; then
    filename="${i%%.*}"
    if [ ! -d "$filename" ]; then
      mkdir "$filename"
    fi

    mv "$i" "$filename"
  fi

done

e.g.

$ tree /somedir
/somedir
├── example-1.pdf
├── example-3.mov
├── file-1.ai
├── file-1.pdf
├── file-1.svg
├── file-2.ai
├── file-2.svg
├── file-2.txt
├── file-3.ai
└── file-3.svg

$ ./above_script

$ tree /somedir
/somedir
├── example-1
│   └── example-1.pdf
├── example-3
│   └── example-3.mov
├── file-1
│   ├── file-1.ai
│   ├── file-1.pdf
│   └── file-1.svg
├── file-2
│   ├── file-2.ai
│   ├── file-2.svg
│   └── file-2.txt
└── file-3
    ├── file-3.ai
    └── file-3.svg 

There are many ways this can be done. One solution would be to simply use the move command:

mv file-1.* /new/directory

This will move all files named file-1 regardless of extension to the new directory.

Consider this script:

for i in *.*; do
   d="${i%.*}"
   [[ ! -d "$d" ]] && mkdir "$d"
   cp "$i" "$d"
done
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!