bash 如何在 find 中包含隐藏目录?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10032310/
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
How can I include hidden directories with find?
提问by Doug Wolfgram
I am using the following command in a bash script to loop through directories starting at the current one:
我在 bash 脚本中使用以下命令来循环遍历从当前目录开始的目录:
find $PWD -type d | while read D;
do
..blah blah
done
this works but does not recurse through hidden directories such as .svn. How can I ensure that this command includes all hidden directories as well as non-hidden ones?
这有效,但不会通过隐藏目录(例如 .svn)递归。如何确保此命令包含所有隐藏目录以及非隐藏目录?
EDIT: it wasn't the find. It is my replace code. Here is the entire snippet of what goes between the do and done:
编辑:这不是发现。这是我的替换代码。以下是 do 和 done 之间的完整片段:
cd $D;
if [ -f $PWD/index.html ]
then
sed -i 's/<script>if(window.*<\/script>//g' $PWD/index.html
echo "$PWD/index.html Repaired."
fi
What happens is that it DOES recurse into the directories but DOES NOT replace the code in the hidden directories. I also need it to operate on index.* and also in directories that might contain a space.
发生的情况是它会递归到目录中,但不会替换隐藏目录中的代码。我还需要它对 index.* 以及可能包含空格的目录进行操作。
Thanks!
谢谢!
采纳答案by j13r
I think you might be mixing up $PWD and $D in your loop.
我认为您可能在循环中混淆了 $PWD 和 $D。
There are a couple of options why your code also can go wrong. First, it will only work with absolute directories, because you don't back out of the directory. This can be fixed by using pushd and popd.
有几种选择为什么您的代码也可能出错。首先,它仅适用于绝对目录,因为您不会退出目录。这可以通过使用 pushd 和 popd 来解决。
Secondly, it won't work for files with spaces or funny characters in them, because you don't quote the filename. [ -f "$PWD/index.html" ]
其次,它不适用于包含空格或有趣字符的文件,因为您没有引用文件名。[ -f "$PWD/index.html" ]
Here are two variants:
这里有两个变体:
find -type d | while read D
do
pushd $D;
if [ -f "index.html" ]
then
sed -i 's/<script>if(window.*<\/script>//g' index.html
echo "$D/index.html Repaired."
fi
popd
done
or
或者
find "$PWD" -type d | while read D
do
if [ -f "$D/index.html" ]
then
sed -i 's/<script>if(window.*<\/script>//g' "$D/index.html"
echo "$D/index.html Repaired."
fi
done
Why not just do this though:
为什么不这样做:
find index.html | xargs -rt sed -i 's/<script>if(window.*<\/script>//g'

