【发布时间】:2012-05-11 14:02:04
【问题描述】:
我是 Linux 的新手,也是编程的初学者,但已经能够将几行代码拼凑在一起 here 用于将文件列表传递给 for 循环,here 用于对文件夹做同样的事情。
# Run search.sh from base folder;
# Only interested in folders under base folder (e.g., baseFolder/FolderA)
# list all folders in base directory that match search parameters;
# cut out just the folder name; feed to variable DIR
DIR=$(find . -name *MTL.txt | cut -d '/' -f2)
# echo $DIR = "FolderA FolderB FolderC"
# place that information in a for-loop
for i in $DIR; do
cd $DIR # step into folder
# find specific file in folder for processing
FILE=$(find -name *MTL | cut -d '/' -f2)
# copy in a static file from another folder;
# rename file based on file name found in previous step
cp /baseFolder/staticfile.txt $FILE.new
do more stuff
cd .. # step out of directory
done
第一个目录的代码可以正常完成,但无法移动到后续目录。我猜我的(许多)问题之一是我不能像我一样将文件夹名称列表传递给 $DIR 。这应该很简单,但我的 foo 很弱。
请老师给我指路。
编辑:
将“cd $DIR”更改为“cd $i”具有预期的效果。代码现在循环遍历所有目录并在每个目录中正确执行操作。 - 感谢 core1024 标记上述内容。
【问题讨论】:
-
顺便说一句......你不要错过一个点'。'在 'FILE=$(find -name *MTL | cut -d '/' -f2) ' 之后 'find'?
-
我不是专家,但我认为
cd $DIR # step into folder应该是cd $i # step into folder -
@core1024:我只是面对手掌。在我的代码中更改这件小事使一切正常!您可以发布作为答案吗?谢谢。
-
@SkippyFastol:我删除了“。”在 find 命令中,这两种方式都没有区别。我的理解是,它是为了将 find 命令保留在当前目录中?