开发者

rename multiple file in a sequence c# or c++

开发者 https://www.devze.com 2023-04-02 10:48 出处:网络
How can I rename multiple files like this: file.txt , anotherfile.txt , log.tx开发者_如何学Ct into something like this :

How can I rename multiple files like this:

file.txt , anotherfile.txt , log.tx开发者_如何学Ct

into something like this :

file1.txt , file2.txt , file3.txt

How can I do this in c# or in c++ ?


Use File.Move Method as:

IEnumerable<FileInfo> files = GetFilesToBeRenamed();
int i = 1;
foreach(FileInfo f in files)
{
    File.Move(f.FullName, string.Format("file{0}.txt", i));
    i++;
}

And if f is a fullpath, then you can do this instead:

File.Move(f.FullName, 
         Path.Combine(f.Directory.ToString(), string.Format("file{0}.txt", i));


This would work in you're using an sh-based shell:

#!/bin/sh
FEXT="txt"      # This is the file extension you're searching for
FPRE="file"     # This is the base of the new files names file1.txt, file2.txt, etc.
FNUM=1;         # This is the initial starting number

find . -name "*.${FEXT}" | while read OFN ; do
    # Determine new file name
    NFN="${FPRE}${FNUM}.${FEXT}"
    # Increment FNUM
    FNUM=$(($FNUM + 1))
    # Rename File
    mv "${OFN}" "${NFN}"
done

The script in action:

[james@fractal renfiles]$ touch abc.txt
[james@fractal renfiles]$ touch test.txt
[james@fractal renfiles]$ touch "filename with spaces.txt"
[james@fractal renfiles]$ ll
total 4
-rw-rw-r-- 1 james james   0 Sep  3 17:45 abc.txt
-rw-rw-r-- 1 james james   0 Sep  3 17:45 filename with spaces.txt
-rwxrwxr-x 1 james james 422 Sep  3 17:41 renfiles.sh
-rw-rw-r-- 1 james james   0 Sep  3 17:45 test.txt
[james@fractal renfiles]$ ./renfiles.sh 
[james@fractal renfiles]$ ll
total 4
-rw-rw-r-- 1 james james   0 Sep  3 17:45 file1.txt
-rw-rw-r-- 1 james james   0 Sep  3 17:45 file2.txt
-rw-rw-r-- 1 james james   0 Sep  3 17:45 file3.txt
-rwxrwxr-x 1 james james 422 Sep  3 17:41 renfiles.sh


In c++, you will eventually use

std::rename(frompath, topath);

to perform the action. TR2 proposal N1975 covers this function. However, until then, use boost::rename for the immediate future, and tr2::rename for the period after approval before final placement.

Loop through and use whatever names you want. Don't quite know if you're trying to add numbers, because the current question says 1, 2, 2.


In c# you can use File.Move(source, dest)

Of course you can do it programatically:

string[] files = new string[] {"file.txt" , "anotherfile.txt" , "log.txt"}:
int index = 0;
string Dest;
foreach (string Source in files)
{
   if (!Files.Exists(Source )) continue;
   do {
       index++;
       Dest= "file"+i+".txt";
   } while (File.Exists(NewName);

   File.Move(Source , Dest); 
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号