将文件夹名称连接到文件中

时间:2015-10-28 16:11:16

标签: bash terminal

如果我有一堆文件夹(f1,f2,f3)并且它们都有图像(image1.jpg,image2.jpg) - 我想将文件夹名称添加到图像名称本身

即:f1_image1.jpg

最好的方法是什么?我最好能在终端上运行。

3 个答案:

答案 0 :(得分:2)

这样的东西?

for dir in *
do
    for image in ${dir}/*.jpg
    do
        # remove the 'echo' if you think this works for you
        echo mv "${image}" "${dir}_$(basename ${image})"
    done
done

答案 1 :(得分:0)

这对我有用:

for dir in * 
do
    for image in ${dir}/*.jpg
    do
        image_name=$(echo ${image} | cut -f2 -d/)
        mv "${image}" "${dir}_${image_name}"
    done
done

答案 2 :(得分:0)

基于find的一些衬垫

find <path> -type f -exec  sh -c 'mv {} $(dirname {})/$(basename $(dirname {}))_$(basename {})' \;

其中<path>是一堆文件夹的根文件夹

示例:

创建示例文件

mkdir -p /tmp/ffff/f{1,2,3} 
touch /tmp/ffff/f{1,2,3}/image{1,2,3,4}.jpg

运行

find /tmp/ffff -type f

你会得到

/tmp/ffff/f3/image4.jpg
/tmp/ffff/f3/image3.jpg
/tmp/ffff/f3/image2.jpg
/tmp/ffff/f3/image1.jpg
/tmp/ffff/f2/image4.jpg
/tmp/ffff/f2/image3.jpg
/tmp/ffff/f2/image2.jpg
/tmp/ffff/f2/image1.jpg
/tmp/ffff/f1/image4.jpg
/tmp/ffff/f1/image3.jpg
/tmp/ffff/f1/image2.jpg
/tmp/ffff/f1/image1.jpg

运行

find /tmp/ffff -type f -exec  sh -c 'mv {} $(dirname {})/$(basename $(dirname {}))_$(basename {})' \; 

再次跑步

find /tmp/ffff -type f

你会得到

/tmp/ffff/f3/f3_image1.jpg
/tmp/ffff/f3/f3_image2.jpg
/tmp/ffff/f3/f3_image3.jpg
/tmp/ffff/f3/f3_image4.jpg
/tmp/ffff/f2/f2_image1.jpg
/tmp/ffff/f2/f2_image2.jpg
/tmp/ffff/f2/f2_image3.jpg
/tmp/ffff/f2/f2_image4.jpg
/tmp/ffff/f1/f1_image1.jpg
/tmp/ffff/f1/f1_image2.jpg
/tmp/ffff/f1/f1_image3.jpg
/tmp/ffff/f1/f1_image4.jpg