-2

我需要你的帮助。

我希望能够有一个文件命名系统来检测文件名是否存在以及它是否会自动在其末尾添加一个数字。从 2 开始

IE。

var myString = "2011-1234567";

myString = myString + "-2";

if (2011-1234567-2 already exists) then output new file number as: 2011-1234567-3 

所以 id 希望能够在理想情况下创建一个函数,如果文件名已经存在,该函数会在其末尾自动添加一个数字

4

3 回答 3

0

这个一般。。。

var base_filename = "file"
var i = 0;

function newFileName(){
    i++;
    var filename = base_filename + "-" +i;
    return filename;
}

所以你会像这样使用它:

var new_file = newFileName();

同样,这是非常通用的。玩弄它一些。

于 2012-09-06T16:08:43.200 回答
0
var exists = 0
function file_exists(name) {
   // replace with something suitable for your environment
   exists = 1 - exists 
   return exists
}

function new_name(suggested) {
   // just return back new name if it available
   if (!file_exists(suggested)) { return suggested }
   // try to split name to "base" and "index" parts
   var have_index = suggested.match(/^(.+)\-(\d+)$/)
   var unused_index
   if (have_index && have_index[2]) {
      base = have_index[1]
      unused_index = ++have_index[2]
   } else {
      // use entire name and start from index 2 if not found
      base = suggested
      unused_index = 2
   }
   // loop until you find next free index
   while (file_exists(base  + "-" + unused_index)) { unused_index++ }
   // ... and return result
   return base  + "-" + unused_index
}

运行new_name("tommy"),给出“tommy-2”。new_name("tommy-2")- “tommy-3”等。当然你需要在file_exists函数中定义你自己对“exists”的看法。

于 2012-09-06T16:30:23.037 回答
0

javascript中的文件命名系统?你在使用 node.js 吗?如果没有,则使用此 bash 脚本:

#!/bin/bash
filename= tommy
i=0
for file in *
i++
 do mv "$filename" "${filename}-i"
done
于 2012-09-06T16:41:57.760 回答