2

I am in the process of merging efforts with another developer. I am using UpperCamelCasing, but we decided to follow Google's HTML style guide in using lower case and separating words with hyphens. This decision requires me to rename quite some files on my filesystem. I first though this to be easy since I often use bash for renaming large collections of files. Unfortunately renaming on the Casing style appeared to be a bit more complicating and I did not manage to find an approach.

Can I convert files from one naming convention to another with Bash?

4

3 回答 3

6

尝试使用rename带有-f选项的命令来重命名具有所需替换的文件。

rename -f 's/([a-z])([A-Z])/$1-$2/g; y/A-Z/a-z/' <list_of_files>

如果你还想提取<list_of_files>一些模式,比如说 extension .ext,你需要结合find上面的命令使用xargs

find -type f -name "*.ext" -print0 | xargs -0 rename -f 's/([a-z])([A-Z])/$1-$2/g; y/A-Z/a-z/'

例如,如果你想重命名所有文件pwd

$ ls
dash-case
lowerCamelCase
UpperCamelCase

$ rename -f 's/([a-z])([A-Z])/$1-$2/g; y/A-Z/a-z/' *

$ ls
dash-case
lower-camel-case
upper-camel-case
于 2013-10-07T19:15:54.180 回答
2

尝试这个:

for FILE in *; do NEWFILE=$((sed -re 's/\B([A-Z])/-\1/g' | tr [:upper:] [:lower:]) <<< "$FILE"); if [ "$NEWFILE" != "$FILE" ]; then echo mv \""$FILE"\" \""$NEWFILE"\"; fi; done

这应该会为您提供标准输出上的“mv”语句列表。仔细检查它们是否正确,然后只需添加| bash到语句的末尾即可运行它们。

它是如何工作的?

for FILE in *; do
  NEWFILE=$((sed -re 's/\B([A-Z])/-\1/g' | tr [:upper:] [:lower:]) <<< "$FILE")
  if [ "$NEWFILE" != "$FILE" ]; then
    echo mv \""$FILE"\" \""$NEWFILE"\"
  fi
done

遍历当前目录中的for FILE in *所有文件,承认有多种方法可以遍历所有文件。sed 语句只匹配大写字母,根据\B,不在单词边界上(即在字符串的开头)。由于这种选择性匹配,在单独调用tr. 最后,条件确保您只看到更改的文件名,并且使用技巧echo确保您不会在没有先看到它们的情况下对文件系统进行更改。

于 2013-10-07T19:21:46.053 回答
-1

我遇到了一个类似的问题,根据一个答案,我得出了以下解决方案。它不是一个完整的 Bash 解决方案,因为它依赖于 perl,但因为它完成了我分享它的技巧。

ls  |for file in `xargs`; do mv $file `echo $file | perl -ne 'print lc(join("-", split(/(?=[A-Z])/)))'`; done
于 2013-10-07T19:22:55.260 回答