简体   繁体   English

重命名 shell 脚本中的文件

[英]Rename files in shell script

I have several files like:我有几个文件,例如:

NEW_YORK_CITY_124.txt

ATLANTA_23.txt

BOSTON_DOWNTOWN_67.txt

'Phoenix River_012.txt'

'MIAMI Ocean-Drive_987.txt'

I would like to rename all the files by removing the underscore, space or hyphen in the name (with caps for the first letter of each word) but keeping it for the number, like:我想通过删除名称中的下划线、空格或连字符(每个单词的第一个字母大写)来重命名所有文件,但将其保留为数字,例如:

NewYorkCity_124.txt

Atlanta_23.txt

BostonDowntown_67.txt

PhoenixRiver_012.txt

MiamiOceanDrive_987.txt

Thank you very much for your help.非常感谢您的帮助。

Using GNU sed:使用 GNU sed:

for i in *; do
    ext=${i##*.}
    name=${i%.*}

    name=$(echo "$name" |
    sed -E '
    s/.*/\L&/
    s/(^|[^[:alnum:]]+)(.?)/\U\2/g
    s/[0-9]+$/_&/')

    echo mv "$i" "$name.$ext"
done

This method is a bit inefficient, because it starts a new sed process for each name.这种方法效率有点低,因为它为每个名称启动一个新的 sed 进程。 But it does the job.但它完成了这项工作。 There are some rename programs that have similar syntax to a sed substitution, you could also try one of those, with a similar a expression.有一些重命名程序具有与 sed 替换类似的语法,您也可以尝试其中一个,使用类似的 a 表达式。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM