2012-09-06 41 views
-2

我需要你的帮助。数字文件命名系统

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

即,

var myString = "2011-1234567"; 

myString = myString + "-2"; 

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

所以我还想最好能够创建一个函数如果文件已经存在

+4

如果它存在的地方?在服务器上?在客户端?你有什么尝试?你遇到什么问题? – PeeHaa

+0

您通常无法访问文件系统。 – SoonDead

+0

-1因为没有拿出一个体面的描述。 – PeeHaa

回答

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函数中定义您自己的“存在”愿景。

+0

哇.. ..非常感谢Oleg!这样可以节省很多时间。 –

0

这是非常一般会自动在它的末尾添加了一些...

var base_filename = "file" 
var i = 0; 

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

所以,你会使用这样的:

var new_file = newFileName(); 

再次,这是非常通用的。玩一下它。

+0

非常感谢这个MalSu,我怎样才能让它自动增加数字每次相同fileno存在(见修改后的例子)谢谢一堆Jay –

+0

我编辑的代码,看看它是否检查出你(: – MalSu

0

JavaScript中的文件命名系统?你在使用node.js吗? 如果不是然后使用这个bash脚本:

#!/bin/bash 
filename= tommy 
i=0 
for file in * 
i++ 
do mv "$filename" "${filename}-i" 
done 
相关问题