raptor96 raptor96 - 5 months ago 14
Bash Question

Rename all files within a folder prefixed with foldername

I have a bunch of directories each having multiple files.

dir1
|- part1.txt
|- part2.txt . . .

dir2
|- part1.txt
|- part2.txt . . .


I want to rename the internal files (
part1.txt
and so on) to something like (
dir1_part1.txt
). How can this be done in ubuntu?

This question explains how suffix prefix can be added or removed. But how do I add a prefix as a Directory Name?

Answer

There is a tool called perl-rename sometimes called rename, not to be confused with rename from util-linux. This tool takes a perl expression and renames accordently:

perl-rename 's~/~_~' dir1/* dir2/*

The above will rename and move all files in dir1 and dir2 to the following:

dir1/file1 -> dir1_file1
dir1/file2 -> dir1_file2
dir1/file3 -> dir1_file3

You can play with the regex online