Reputation: 33
I have about 1000 files (they are not .txt, but they do contain text) that I want to move into subdirectories based on a specific part of the content of the files. Each line contains one or more copies of the string
DTM+137:20131001
where the last eight digits are a date. I want to move a file with the above string to a subfolder named \01.10.2013\
. Finding the string is easy enough with regex, but I don't have enough experience with any language to make it all work. I tried with Perl, but I didn't get very far.
Upvotes: 1
Views: 276
Reputation: 5664
If you have a string like
$line = "DTM+137:20131001";
you can extract the month, day and year from it with a grouped regex like this:
($year, $month, $day) = $line =~ /:(\d\d\d\d)(\d\d)(\d\d)$/;
Once you have those, you can use them to build a new directory name:
$new_folder = sprintf("/some/directory/%02d.%02d.%04d", $day, $month, $year);
Create the new directory just in case:
mkdir 0755, $new_folder;
and use the rename
call to move the file there:
rename $file, "$new_folder/$file";
This will probably need some adjustment for your particular problem, but it should help you get started.
Upvotes: 1