在linux中recursion地find多个文件并重命名

我有一个Suse 10系统中的文件,如a_dbg.txt, b_dbg.txt ... 我想编写一个bash shell脚本,通过从这些脚本中删除“_dbg”来重命名这些文件。

谷歌build议我使用rename命令。 所以我在CURRENT_FOLDER上执行了命令rename _dbg.txt .txt *dbg*

我的实际CURRENT_FOLDER包含下面的文件。

 CURRENT_FOLDER/a_dbg.txt CURRENT_FOLDER/b_dbg.txt CURRENT_FOLDER/XX/c_dbg.txt CURRENT_FOLDER/YY/d_dbg.txt 

执行rename命令后,

 CURRENT_FOLDER/a.txt CURRENT_FOLDER/b.txt CURRENT_FOLDER/XX/c_dbg.txt CURRENT_FOLDER/YY/d_dbg.txt 

它没有recursion地做,如何使这个命令重命名所有子目录中的文件。 像XXYY一样,我将拥有许多不可预知的子目录。 而且我的CURRENT_FOLDER也将有一些其他的文件。

您可以使用find来recursion查找所有匹配的文件:

 $ find . -iname "*dbg*" -exec rename _dbg.txt .txt '{}' \; 

编辑:什么'{}'\; 是?

-exec参数使find的每个find的匹配文件执行rename'{}'将被replace为文件的path名称。 最后一个标记\; 是否只有标记execexpression式的结束。

所有这一切都很好地描述在寻找的手册页:

  -exec utility [argument ...] ; True if the program named utility returns a zero value as its exit status. Optional arguments may be passed to the utility. The expression must be terminated by a semicolon (``;''). If you invoke find from a shell you may need to quote the semicolon if the shell would otherwise treat it as a control operator. If the string ``{}'' appears anywhere in the utility name or the argu- ments it is replaced by the pathname of the current file. Utility will be executed from the directory from which find was executed. Utility and arguments are not subject to the further expansion of shell patterns and constructs. 

与bash:

 shopt -s globstar nullglob rename _dbg.txt .txt **/*dbg* 

我写了一个小脚本,用.txt扩展名将所有文件replace为/ tmp下的.cpp扩展名和recursion的子目录

 #!/bin/bash for file in $(find /tmp -name '*.txt') do mv $file $(echo "$file" | sed -r 's|.txt|.cpp|g') done 

对于recursion重命名,我使用下面的命令:

 find -iname \*.* | rename -v "s/ /-/g" 

上面的Scipt可以写成一行:

 find /tmp -name "*.txt" -exec bash -c 'mv $0 $(echo "$0" | sed -r \"s|.txt|.cpp|g\")' '{}' \; 

如果你只是想重命名,不介意使用外部工具,那么你可以使用rnm 。 该命令将是:

 #on current folder rnm -dp -1 -fo -ssf '_dbg' -rs '/_dbg//' * 

-dp -1将使其recursion到所有子目录。

-fo意味着仅文件模式。

-ssf '_dbg'在文件名中search带有_dbg的文件。

-rs '/_dbg//'用空stringreplace_dbg。

您也可以使用CURRENT_FOLDER的path运行上述命令:

 rnm -dp -1 -fo -ssf '_dbg' -rs '/_dbg//' /path/to/the/directory 

你可以在下面使用这个。

 rename --no-act 's/\.html$/\.php/' *.html */*.html 

经典scheme:

 for f in $(find . -name "*dbg*"); do mv $f $(echo $f | sed 's/_dbg//'); done