Bash loop through directory and rename every file

妖精的绣舞 提交于 2019-12-24 00:33:02

问题


I am horrible at writing bash scripts, but I'm wondering if it's possible to recursively loop through a directory and rename all the files in there by "1.png", "2.png", etc, but I need it to restart at one for every new folder it enters. Here's script that works but only does it for one directory.

cd ./directory
cnt=1
for fname in *
do
    mv $fname ${cnt}.png
    cnt=$(( $cnt + 1 ))
done

Thanks in advance

EDIT Can anyone actually write this code out? I have no idea how to write bash, and it's very confusing to me


回答1:


Using find is a great idea. You can use find with the next syntax to find all directories inside your directory and apply your script to found directories:

find /directory -type d -exec youscript.sh {} \;

-type d parameter means you want to find only directories

-exec youscript.sh {} \; starts your script for every found directory and pass it this directory name as a parameter




回答2:


Use find(1) to get a list of files, and then do whatever you like with that list.



来源:https://stackoverflow.com/questions/8131146/bash-loop-through-directory-and-rename-every-file

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!