重命名文件时性能使用bash循环 [英] Performance with bash loop when renaming files
问题描述
有时候,我需要重命名文件,如增加preFIX或删除的东西一定量。
起初,我写了一个python脚本。它运作良好,我想一个shell版本。因此,我写了这样的事情:
Sometimes I need to rename some amount of files, such as add a prefix or remove something. At first I wrote a python script. It works well, and I want a shell version. Therefore I wrote something like that:
$ 1 - 列出的目录,
$ 2 - 什么花样会更换,
$ 3 - 更换
$1 - which directory to list, $2 - what pattern will be replacement, $3 - replacement.
echo "usage: dir pattern replacement"
for fname in `ls $1`
do
newName=$(echo $fname | sed "s/^$2/$3/")
echo 'mv' "$1/$fname" "$1/$newName&&"
mv "$1/$fname" "$1/$newName"
done
它的工作原理,但非常缓慢,可能是因为它需要创建一个进程(这里 SED
和 MV
)和摧毁它,然后再次创建相同的过程正好有一个不同的观点。真的吗?如果是这样,如何避免它,我怎么能获得更快的版本?
It works but very slowly, probably because it needs to create a process (here sed
and mv
) and destroy it and create same process again just to have a different argument. Is that true? If so, how to avoid it, how can I get a faster version?
我想提供所有处理过的文件名(使用 SED
来一次处理它们),但它仍然需要 MV
中的循环。
I thought to offer all processed files a name (using sed
to process them at once), but it still needs mv
in the loop.
请告诉我,你们是怎么做到的?谢谢。如果你发现我的问题难以理解,请耐心等待,我的英语不太好,不好意思。
Please tell me, how you guys do it? Thanks. If you find my question hard to understand please be patient, my English is not very good, sorry.
--- ---更新
我对我的描述遗憾。我的核心问题是:如果我们应该循环使用某些命令,将较低的表现?因为在为我在{} 1..100000; LS做1 GT;的/ dev / null的;做
创建和销毁过程将花费大部分时间。所以,我想什么是有什么办法,以减少成本呢?
I am sorry for my description. My core question is: "IF we should use some command in loop, will that lower performance?" Because in for i in {1..100000}; do ls 1>/dev/null; done
creating and destroying a process will take most of the time. So what I want is "Is there any way to reduce that cost?".
感谢千电子伏和S.R.I给我一个改名
解决方案来重命名文件。
Thanks to kev and S.R.I for giving me a rename
solution to rename files.
推荐答案
每次调用外部二进制文件( LS
, SED
, MV
),bash有叉本身给exec命令而这需要一个大的性能损失。
Every time you call an external binary (ls
, sed
, mv
), bash has to fork itself to exec the command and that takes a big performance hit.
您可以做你想做纯粹的bash 4.X做的一切,只需要调用 MV
You can do everything you want to do in pure bash 4.X and only need to call mv
pat_rename(){
if [[ ! -d "$1" ]]; then
echo "Error: '$1' is not a valid directory"
return
fi
shopt -s globstar
cd "$1"
for file in **; do
echo "mv $file ${file//$2/$3}"
done
}
这篇关于重命名文件时性能使用bash循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!