如何在 Linux 中重命名大量文件,为每个文件更改相同的文件名元素



我正在尝试重命名大量文件(我数了 200 多),这些文件要么在文件名中,要么在文本内容中都有公司名称。我基本上需要将任何对"公司"的引用更改为"新公司",在适用的情况下保持大写(即"公司成为新公司","公司"变为"新公司")。我需要递归地执行此操作。

因为这个名字几乎可以出现在任何地方,所以我无法在任何地方找到符合我要求的示例代码。它可以是这些示例中的任何一个例子,也可以是更多:

company.jpg
company.php
company.Class.php
company.Company.php
companysomething.jpg

希望你明白了。我不仅需要对文件名执行此操作,还需要使用文本文件的内容,例如 HTML 和 PHP 脚本。我假设这将是第二个命令,但我不完全确定是什么。

我搜索了代码库,在近 2000 个文件中发现了近 300 次提到公司名称,所以我不喜欢手动进行。

请帮忙!:)

bash具有强大的循环和替换功能:

for filename in `find /root/of/where/files/are -name *company*`; do
    mv $filename ${filename/company/newcompany}
done
for filename in `find /root/of/where/files/are -name *Company*`; do
    mv $filename ${filename/Company/Newcompany}
done

对于文件和目录名称,请使用 forfindmvsed

对于名称中包含company的每个路径(f),将其重命名(mv)从f到新名称,其中company替换为newcompany

for f in `find -name '*company*'` ; do mv "$f" "`echo $f | sed s/company/nemcompany/`" ; done

对于文件内容,请使用 findxargssed

对于每个文件,通过newcompany其内容来更改company,保留带有扩展名.backup的原始文件。

find -type f -print0 | xargs -0 sed -i .bakup 's/company/newcompany/g'

我建议你看看man rename一个非常强大的perl实用程序,用于重命名文件。

标准语法为

rename 's/.htm$/.html/' *.htm

聪明的部分是该工具接受任何Perl-Regexp作为要更改文件名的模式。

您可能希望使用 -n 开关运行它,这将使该工具仅报告它将更改的内容。

现在找不到保持大写的好方法,但由于您已经可以搜索文件结构,因此发出几个具有不同大小写的rename,直到所有文件都更改为止。

要遍历当前文件夹下的所有文件并搜索特定字符串,您可以使用

find . -type f -exec grep -n -i STRING_TO_SEARCH_FOR /dev/null {} ;

该命令的输出可以定向到文件(经过一些过滤以提取需要更改的文件的文件名)。

find . /type ... > files_to_operate_on

然后将其包装在一个while read循环中,并做一些perl魔法来就地替换。

while read file
do
    perl -pi -e 's/stringtoreplace/replacementstring/g' $file
done < files_to_operate_on

归处理文件的正确方法很少。这是其中之一:

while IFS= read -d $'' -r file ; do
    newfile="${file//Company/Newcompany}"
    newfile="${newfile//company/newcompany}"
    mv -f "$file" "$newfile"
done < <(find /basedir/ -iname '*company*' -print0)

这将适用于所有可能的文件名,而不仅仅是其中没有空格的文件名。

假定是 bash。

对于更改文件的内容,我建议谨慎,因为如果文件不是纯文本,则文件中的盲目替换可能会破坏内容。也就是说,sed是为这种事情而生的。

while IFS= read -d $'' -r file ; do
    sed -i '' -e 's/Company/Newcompany/g;s/company/newcompany/g'"$file"
done < <(find /basedir/ -iname '*company*' -print0)

对于此运行,我建议添加一些额外的开关find以限制它将处理的文件,也许

find /basedir/ ( -iname '*company*' -and ( -iname '*.txt' -or -ianem '*.html' ) ) -print0

最新更新