Shell Script for renaming and relocating the files

2019-07-19 04:50发布

I am working on something and need to solve the following. I am giving a analogous version of mine problem.

Say we have a music directory, in which there are 200 directories corresponding to different movies. In each movie directory there are some music files.

Now, say a file music.mp3 is in folder movie.mp3 . I want to make a shell script such that it renames the file to movie_music.mp3 and put it in some folder that I mention to it. Basically, all the files in the subdirectories are to be renamed and to be put in a new directory.

Any workaround for this?

3条回答
姐就是有狂的资本
2楼-- · 2019-07-19 05:32

This script receives two arguments: the source folder and the destination folder. It will move every file under any directory under the source directory to the new directory with the new filename:

#!/bin.sh
echo "Moving from $1 to $2"
for dir in "$1"/*; do
  if [ -d "$dir" ]; then
    for file in "$dir"/*; do
      if [ -f "$file" ]; then
        echo "${file} -> $2/`basename "$dir"`_`basename "${file}"`"
        mv "${file}" "$2"/`basename "$dir"`_`basename "${file}"`
      fi
    done
  fi
done

Here is a sample:

bash move.sh dir dir2
Moving from dir to dir2
dir/d1/f1 -> dir2/d1_f1
dir/d1/f2 -> dir2/d1_f2
dir/d2/f1 -> dir2/d2_f1
dir/d2/f2 -> dir2/d2_f2
查看更多
狗以群分
3楼-- · 2019-07-19 05:33

Assuming the following directory tree:

./movie1:
movie1.mp3

./movie2:
movie2.mp3

The following one-liner will create 'mv' commands you can use:

find ./ | grep "movie.*/" | awk '{print "mv "$1" "$1}' | sed 's/\(.*\)\//\1_/'

EDIT:

If your directory structure contains only the relevant directories, you can expand use the following grep instead:

grep "\/.*\/.*"

Notice it looks file anything with at least one directory and one file. If you have multiple inner directories, it won't be good enough.

查看更多
兄弟一词,经得起流年.
4楼-- · 2019-07-19 05:43

Bash:

newdir=path/to/new_directory;
find . -type d |while read d; do
  find "$d" -type f -maxdepth 1 |while read f; do
    movie="$(basename "$d" |sed 's/\(\..*\)\?//')"
    mv "$f" "$newdir/$movie_$(basename $f)";
  done;
done
查看更多
登录 后发表回答