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

Python 更改bash中具有特殊字符的文件名,python,bash,perl,batch-rename,Python,Bash,Perl,Batch Rename,我们正在运行一个Ubuntu服务器,自动从客户那里获取FTPs文件,最近这些文件显示为。。。 'file.csv;' 'file2.csv 我一直在尝试,但没有运气,没有运气地制定bash和Python解决方案。我只是想去掉单引号和分号,保留剩下的。这不一定是bash,它可以是python甚至perl。我在下面列出了不起作用的代码。我甚至连目录清单都找不到。谁能给我指出正确的方向吗 for i in \'* do echo $i done 注意:已更正代码以删除错误的$ech

我们正在运行一个Ubuntu服务器,自动从客户那里获取FTPs文件,最近这些文件显示为。。。 'file.csv;' 'file2.csv

我一直在尝试,但没有运气,没有运气地制定bash和Python解决方案。我只是想去掉单引号和分号,保留剩下的。这不一定是bash,它可以是python甚至perl。我在下面列出了不起作用的代码。我甚至连目录清单都找不到。谁能给我指出正确的方向吗

for i in \'* 
    do
    echo $i
done

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

使用
查找-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
有多种风格。他们中的大多数人应该为这项任务工作。我使用了亚里士多德·帕格尔茨的1.601版。要安装
重命名
,只需下载其Perl脚本并放入
$PATH
。或者使用
conda
安装
rename
,如下所示:

conda install rename

使用Python,您可以首先尝试这个pyhon3脚本。不过我只在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))

使用。如果用正确的shebang粘贴代码,它会告诉您试图使用
echo
作为变量,这可能不是您想要的。您可以重命名它们,然后执行此操作
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))