Linux 在文件中找到一个模式并重命名它们
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15290186/
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
find a pattern in files and rename them
提问by mahmood
I use this command to find files with a given pattern and then rename them to something else
我使用此命令查找具有给定模式的文件,然后将它们重命名为其他名称
find . -name '*-GHBAG-*' -exec bash -c 'echo mv mv ./report-GHBAG-1B ./report-stream-agg-1B
mv ./reoprt-GHBAG-0.5B ./report-stream-agg-0.5B
${0/GHBAG/stream-agg}' {} \;
As I run this command, I see some outputs like this
当我运行这个命令时,我看到了一些这样的输出
find . -name '*-GHBAG-*' -exec bash -c 'mv rename 's/GHBAG/stream-agg/' *-GHBAG-*
${0/GHBAG/stream-agg}' {} \;
However at the end, when I run ls
, I see the old file names.
但是最后,当我运行时ls
,我看到了旧文件名。
采纳答案by kamituel
You are echo'ing your 'mv' command, not actually executing it. Change to:
您正在回显您的“mv”命令,而不是实际执行它。改成:
rename 's/GHBAG/stream-agg/' **/*-GHBAG-*
回答by anumi
I would suggest using the rename
command to perform this task. rename
renames the filenames supplied according to the rule specified as a Perl regular expression.
我建议使用该rename
命令来执行此任务。rename
根据指定为 Perl 正则表达式的规则重命名提供的文件名。
In this case, you could use:
在这种情况下,您可以使用:
# bashrc
function file_replace() {
for file in $(find . -type f -name "*"); do
mv $file $(echo "$file" | sed "s///");
done
}
回答by Zac
In reply to anumi's comment, you could in effect search recursively down directories by matching '**':
在回复 anumi 的评论时,您实际上可以通过匹配“**”来递归搜索目录:
file_replace "Slider.js" "RangeSlider.ts"
renamed: packages/react-ui-core/src/Form/Slider.js -> packages/react-ui-core/src/Form/RangeSlider.ts
renamed: stories/examples/Slider.js -> stories/examples/RangeSlider.ts
回答by lfender6445
This works for my needs, replacing all matching files or file types. Be warned, this is a very greedy search
这适合我的需要,替换所有匹配的文件或文件类型。请注意,这是一个非常贪婪的搜索
file_replace Slider RangeSlider
renamed: packages/react-ui-core/src/Form/Slider.js -> packages/react-ui-core/src/Form/RangeSlider.js
renamed: stories/examples/Slider.js -> stories/examples/RangeSlider.js
renamed: stories/theme/Slider.css -> stories/theme/RangeSlider.css
I will usually run with find . -type f -name "MYSTRING*"
in advance to check the matches out before replacing.
我通常会find . -type f -name "MYSTRING*"
提前运行以在更换之前检查匹配项。
For example:
例如:
##代码##or ditch the filetype to make it even greedier
或放弃文件类型以使其更加贪婪
##代码##