cwindowsstringrename

How to use the contents of a text file(tab delimited format) to rename files in a folder?


I'm trying to make e-certificates to distribute for one of my college events. I used Photoshop to generate batch certificates with different names and roll nos. Now the files are named core_01Data Set 1.jpg, core_02Data Set 2.jpg, etc. In order to distribute them online, they need to renamed and sorted wrt the participant's name. I have a .txt file with the participant names, their roll no and college name(in tab delimited format). I need to rename the files according to the content of the .txt file. I have tried my bit but couldn't go far. Please help.

#include<stdio.h>
#include<dirent.h>
int main()
{
    FILE *fp;
    char arr[3][20][40];
    int i=0;

    char final_name[19][50]={0};

    fp = fopen("./new/core.txt", "r");
    while(fgetc(fp)!=EOF)
    {
     while(fgetc(fp)!='\n' && i<20)
     {
        fscanf(fp,"%s%s%s", arr[0][i], arr[1][i], arr[2][i]);
        i++;
     }
    }

    i=1;
    while(i<20)
    {
        strcat(final_name[i-1], arr[0][i]);
        strcat(final_name[i-1], "_");
        strcat(final_name[i-1], arr[1][i]);
        strcat(final_name[i-1], "_");
        strcat(final_name[i-1], arr[2][i]);
        printf("%s\n", final_name[i-1]);
        i++;
    }
    char name[19][50]={0};
    char buf[19][50]={0};

    for(i=1; i<20; i++)
    {
        if(i<10)
        {
            sprintf(buf[i-1], "core_0%d_Data Set %d", i, i);
        }
        else
        {
            sprintf(buf[i-1], "core_%d_Data Set %d", i, i);
        }

        printf("%s...\n", buf[i-1]);
        name[i-1]=buf[i-1];
    }

    i=0;
    DIR *d;
    struct dirent *dir;
    d = opendir("./new/");
    if (d)
    {
        while ((dir = readdir(d)) != NULL )
        {
            printf("%s\n", dir->d_name);
            if (strcmp(dir->d_name, buf[i]) == 0)
            {
                rename(dir->d_name, final_name[i]);
                i++;
            }
        }
        closedir(d);
    }
}

Solution

  • You could use powershell if you want. I think this would work.

    $names = (gc core.txt)
    $idx = 1
    
    gci core*.jpg | %{
        $newname = $names[$idx++].trim().split("`t")[0] + ".jpg"
        ren $_ $newname
    }
    

    Edit: It's this

    .trim().split("`t")[0]
    

    part that splits each line of core.txt on tabs and returns the first element. If you want the other columns included as well, try this:

    $names = (gc core.txt)
    $idx = 1
    
    gci core*.jpg | %{
        $newname = ($names[$idx++].trim() -replace "`t+","-") + ".jpg"
        ren $_ $newname
    }