Shell脚本可将文件夹名称复制并添加到来自多个子目录的文件中 [英] Shell script to copy and prepend folder name to files from multiple subdirectories

查看:683
本文介绍了Shell脚本可将文件夹名称复制并添加到来自多个子目录的文件中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有几个具有不同图像共享文件名的文件夹,其文件夹结构如下:

I have several folders with different images sharing file names, with a folder structure like this:

/parent/folder001/img001.jpg
/parent/folder001/img002.jpg
/parent/folder002/img001.jpg
/parent/folder002/img002.jpg
/parent/folder003/img001.jpg
/parent/folder003/img002.jpg
...

,并希望将这些文件复制/重命名到新文件夹中,如下所示:

and would like to copy/rename these files into a new folder, like this:

/newfolder/folder001_img001.jpg
/newfolder/folder001_img002.jpg
/newfolder/folder002_img001.jpg
/newfolder/folder002_img002.jpg
/newfolder/folder003_img001.jpg
/newfolder/folder003_img002.jpg
...

(如果newfolder不是parent的子文件夹,可能会更好,因为这可能最终导致真正奇怪的递归.)

(It's probably better if newfolder isn't a subfolder of parent, since that might end up causing really weird recursion.)

所有包含图像的文件夹都没有任何子文件夹.

None of the folders containing images have any subfolders.

理想情况下,我希望能够重新使用脚本来更新"新文件夹,因为稍后可能需要添加更多包含文件夹的图像.

Ideally, I'd like to be able to reuse the script to "update" newfolder, since I might need to add more folders-containing-images later along the line.

如何使用shell脚本完成此操作?

How can I accomplish this with a shell script?

推荐答案

这有点乏味,但是可以做到:

This is a bit tedious but will do:

#!/bin/bash
parent=/parent
newfolder=/newfolder
mkdir "$newfolder"
for folder in "$parent"/*; do
  if [[ -d "$folder" ]]; then
    foldername="${folder##*/}"
    for file in "$parent"/"$foldername"/*; do
      filename="${file##*/}"
      newfilename="$foldername"_"$filename"
      cp "$file" "$newfolder"/"$newfilename"
    done
  fi
done

父级路径放入parent变量,将 newfolder 路径放入newfolder变量.

Put the parent path to parent variable and newfolder path to newfolder variable.

这篇关于Shell脚本可将文件夹名称复制并添加到来自多个子目录的文件中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆