为什么这个bash for循环很慢?

时间:2022-10-25 07:38:49

I am trying to this code:

我正在尝试这段代码:

for f in jobs/UPDTEST/apples* ; do
    nf=`echo $f | sed s:jobs\/::g`
    echo $nf | tr '_' ' '
done > jobs

There are 750 apples* type text files. But as I am only messing with the file name - I would have thought it should be quick - but take about 5 mins.

有750个苹果*类型的文本文件。但是因为我只是把文件名弄乱了——我本以为应该很快——但是要花大约5分钟。

Is there an alternative way to do this?

有别的办法吗?

2 个解决方案

#1


3  

You can use parameter expansions like ${parameter/pattern/string} to get rid of the calls to sed and tr. In your case it could look like:

可以使用${parameter/pattern/string}之类的参数扩展来消除对sed和tr的调用。

for f in jobs/UPDTEST/apples*; do
    f=${f//jobs\//}
    echo ${f//_/ }
done > jobs

#2


1  

First, cd jobs would remove the need for the sed

首先,cd作业将消除对sed的需要

Second, you don't need tr to substitute characters in the value of a bash variable.

其次,您不需要tr来替换bash变量值中的字符。

Third, with find you don't need a loop at all.

第三,使用find您根本不需要循环。

f=$(cd jobs; find UPDTEST -name 'apples*' -depth 1)
echo "${f//_/ }" > jobs.log

By the way, you can't have a jobs directory and a jobs file in the same directory.

顺便说一下,您不能在同一个目录中有一个作业目录和一个作业文件。

#1


3  

You can use parameter expansions like ${parameter/pattern/string} to get rid of the calls to sed and tr. In your case it could look like:

可以使用${parameter/pattern/string}之类的参数扩展来消除对sed和tr的调用。

for f in jobs/UPDTEST/apples*; do
    f=${f//jobs\//}
    echo ${f//_/ }
done > jobs

#2


1  

First, cd jobs would remove the need for the sed

首先,cd作业将消除对sed的需要

Second, you don't need tr to substitute characters in the value of a bash variable.

其次,您不需要tr来替换bash变量值中的字符。

Third, with find you don't need a loop at all.

第三,使用find您根本不需要循环。

f=$(cd jobs; find UPDTEST -name 'apples*' -depth 1)
echo "${f//_/ }" > jobs.log

By the way, you can't have a jobs directory and a jobs file in the same directory.

顺便说一下,您不能在同一个目录中有一个作业目录和一个作业文件。