更改bash中具有特殊字符的文件名

问题描述

我们正在运行一个ubuntu服务器,该服务器会自动从客户处FTP文件,而这些文件最近显示为... 'file.csv;' 'file2.csv;

我一直在尝试,没有运气,制定bash和Python解决方案。我只是想去掉单引号和分号,并保留剩下的。这不必是bash,可以是python甚至是perl。我在下面列出了无效的代码。我什至看不到目录清单。谁能指出我正确的方向?

for i in \'* 
    do
    echo $i
done

注意:已更正的代码可以删除错误的$ echo'

解决方法

像这样使用find ... -exec rename

find . -name "*[;']*" -exec rename "tr/';//d" {} \;

示例:

# Create example input files:
$ touch "f'o''o'" "b;a;;r;" "b';a;'';z;'"

# Build the command by first confirming that `find` finds them all:
$ find . -name "*[;']*"                            
./f'o''o'
./b';a;'';z;'
./b;a;;r;

# Find and rename them,one by one:
$ find . -name "*[;']*" -exec rename "tr/';//d" {} \;

# Confirm that rename worked as expected:
$ ls -1rt | tail -n 3                                
foo
bar
baz

您还可以使用xargs对速度进行批量重命名,例如

find ... -print0 | xargs -0 ...

但是在您的情况下,我认为一一重命名文件足够快。


命令行实用程序rename有多种形式。他们中的大多数应为此任务工作。我使用了Aristotle Pagaltzis的rename版本1.601。要安装rename,只需下载其Perl脚本并将其放入$PATH。或使用rename安装conda,如下所示:

conda install rename
,
import os
filesInDirectory = os.listdir(Path)

for filename in filesInDirectory:
    if "'" in filename:
        filename.replace("'","")
    elif ";" in filename:
        filename.replace(";","") 
    elif ("'" and ";") in filename:
        filename.replace("'","")
        filename.replace(";","")

使用Python

,

您可以先尝试使用pyhon 3脚本。我只在Windows中测试过。

import os

folder = ""
for root,dirs,files in os.walk(folder,topdown=False):
    for fn in files:
        path_to_file = os.path.join(root,fn)
        if "'" in fn or ";" in fn:
            print('Removing special characters from file: ' + fn)
            new_name = fn.replace("'",'').replace(";",'') 
            os.rename(path_to_file,os.path.join(root,new_name))