bash 如何去除文件名中的特殊字符?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/40712263/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 15:26:20  来源:igfitidea点击:

How to remove special characters in file names?

linuxbash

提问by Andy

When creating playlists I often came across files that would break the playing process. Such would be files with spaces or apostrophes. I would fix it with the following command

在创建播放列表时,我经常遇到会破坏播放过程的文件。这将是带有空格或撇号的文件。我会用以下命令修复它

for file in *.; do mv "$file" `echo $file | tr " " '_'` ; done **(for spaces)**

Now I more often come across files with commas, apostrophes, brackets and other characters. How would I modify the command to remove such characters?

现在我更经常遇到带有逗号、撇号、方括号和其他字符的文件。我将如何修改命令以删除这些字符?

Also tried rename 's/[^a-zA-Z0-9_-]//' *.mp4but it doesnt seem to remove spaces or commas

也试过了,rename 's/[^a-zA-Z0-9_-]//' *.mp4但似乎没有删除空格或逗号

回答by heemayl

Your renamewould work if you add the gmodifier to it, this performs all substitutions instead of only the first one:

rename如果g向其中添加修饰符,您会工作,这将执行所有替换而不是仅执行第一个替换:

$ echo "$file"
foo bar,spam.egg

$ rename -n 's/[^a-zA-Z0-9_-]//' "$file"
foo bar,spam.egg renamed as foobar,spam.egg

$ rename -n 's/[^a-zA-Z0-9_-]//g' "$file"
foo bar,spam.egg renamed as foobarspamegg


You can do this will bashalone, with parameter expansion:

您可以bash单独执行此操作,并带有参数扩展:

  • For removing everything except a-zA-Z0-9_-from file names, assuming variable filecontains the filename, using character class [:alnum:]to match all alphabetic characters and digits from current locale:

    "${file//[^[:alnum:]_-]/}"
    

    or explicitly, change the LC_COLLATEto C:

    "${file//[^a-zA-Z0-9_-]/}"
    
  • 为了删除除a-zA-Z0-9_-文件名之外的所有内容,假设变量file包含文件名,使用字符类[:alnum:]匹配来自 current 的所有字母字符和数字locale

    "${file//[^[:alnum:]_-]/}"
    

    或明确地,更改LC_COLLATEC

    "${file//[^a-zA-Z0-9_-]/}"
    

Example:

例子:

$ file='foo bar,spam.egg'

$ echo "${file//[^[:alnum:]_-]/}"
foobarspamegg

回答by Jairo Bernal

for file in *; do mv "$file" $(echo "$file" | sed -e 's/[^A-Za-z0-9._-]/_/g'); done &