Sunday, September 28, 2014

command line - Batch rename files in linux using folder name



I have a load of directories (2005 - 2012), each with files (01.jpg - 100.jpg).




If I wanted to rename all the files into the base directory, renamed to, for example, Folder 2005 - 01.jpg, what would be the easiest way of doing this by the command line in Linux?



For example from



/home/mark/images/2005/01.jpg
/home/mark/images/2005/02.jpg
/home/mark/images/2005/03.jpg
/home/mark/images/2006/01.jpg
/home/mark/images/2006/02.jpg
/home/mark/images/2006/03.jpg



to



/home/mark/images/Folder 2005 - 01.jpg
/home/mark/images/Folder 2005 - 02.jpg
/home/mark/images/Folder 2005 - 03.jpg
/home/mark/images/Folder 2006 - 01.jpg
/home/mark/images/Folder 2006 - 02.jpg
/home/mark/images/Folder 2006 - 03.jpg



Surely there must be a simple one liner for this? I know that you can use, e.g. {2005-2012} to access the multiple directories, but I'm not sure how to then access that value later when renaming.


Answer



#!/bin/bash
for year in 20??; do
pushd "$year"
for file in *; do
echo mv "$file" ../"Folder ${year} - ${file}"
done

popd
done


Remove the echo if the output looks good to you.


No comments:

Post a Comment

linux - How to SSH to ec2 instance in VPC private subnet via NAT server

I have created a VPC in aws with a public subnet and a private subnet. The private subnet does not have direct access to external network. S...