Monday, October 12, 2015

macos - Rename files based on folder name


I have lots of index.html files in unique named folders (one per folder).
I wish to rename each file with that of it's parent folder name.


From:


/folder1/index.html
/folder2/index.html
/folder3/index.html
/folder4/index.html
/folder5/index.html

To:


/folder1/folder1.html
/folder2/folder2.html
/folder3/folder3.html
/folder4/folder4.html
/folder5/folder5.html

Attempt 1


I have tried rename -vn 's:(/[^/]*)/[^/]*$:$1$1.html:' folder/*/*.html which returns with:


Using expression: sub { use feature ':5.18'; s:(/[^/]*)/[^/]*$:$1$1.html: }
'folder/*/*.html' unchanged

I don't really understand what's happening to be able to fix it.


Attempt 2


Next, I tried rename -n -v '...' folder/*/*.html, which returned with:


Using expression: sub { use feature ':5.18'; ... }
Unimplemented at (eval 2) line 1.

I am using OSX with rename installed.


Answer



That works for me:


rename -vn 's/([^\/]+)\/index/$1\/$1/' folder*/*.html

Prints:


folder1/index.html renamed as folder1/folder1.html
folder2/index.html renamed as folder2/folder2.html
folder3/index.html renamed as folder3/folder3.html
folder4/index.html renamed as folder4/folder4.html
folder5/index.html renamed as folder5/folder5.html

Another solution with sed:


ls -1 folder*/*.html | sed 's/\([^\/]\+\)\/index.html/mv "\0" "\1\/\1.html"/'

Prints:


mv "folder1/index.html" "folder1/folder1.html"
mv "folder2/index.html" "folder2/folder2.html"
mv "folder3/index.html" "folder3/folder3.html"
mv "folder4/index.html" "folder4/folder4.html"
mv "folder5/index.html" "folder5/folder5.html"

If that prints the correct commands just pipe it to a bash. But first make sure that the printed commands would work before executing it:


ls -1 folder*/*.html | sed 's/\([^\/]\+\)\/index.html/mv "\0" "\1\/\1.html"/' | bash

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...