Move a group of files to a new folder if their fil

2019-04-17 10:41发布

I have a folder full of files that have the same name but different file extensions. For example:

file-1.ai
file-1.svg
file-1.pdf
file-2.ai
file-2.svg
file-2.txt
file-3.ai
file-3.svg
example-1.pdf
example-3.mov

Is there any way in Linux (any programming language will do) I can move the group of files to a new folder (either a new folder per file group or all in one folder) if their file names, minus extension, matches?

3条回答
做个烂人
2楼-- · 2019-04-17 11:39

Consider this script:

for i in *.*; do
   d="${i%.*}"
   [[ ! -d "$d" ]] && mkdir "$d"
   cp "$i" "$d"
done
查看更多
Deceive 欺骗
3楼-- · 2019-04-17 11:43

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 
查看更多
戒情不戒烟
4楼-- · 2019-04-17 11:43

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.

查看更多
登录 后发表回答