![遍历文件('for file in...)并且还包括子目录?](https://linux22.com/image/3538/%E9%81%8D%E5%8E%86%E6%96%87%E4%BB%B6%EF%BC%88'for%20file%20in...%EF%BC%89%E5%B9%B6%E4%B8%94%E8%BF%98%E5%8C%85%E6%8B%AC%E5%AD%90%E7%9B%AE%E5%BD%95%EF%BC%9F.png)
我正在使用 sed 对文件进行大量更改。我认为这个问题与任何想要迭代匹配模式的文件并在原始文件搜索递归和文件创建输出中包含子目录(即创建它们来复制结构)的操作相关
我最初得到的文件是
mkdir -p _seded
for file in *_spec.rb
do
cat $file
... a bunch of seds
> _seded $file
end
我怎样才能获得文件加上子目录与模式匹配的文件?
例如,如果我有
spec/ex1
spec/ex2_spec.rb
spec/subs/subex1
spec/subs/subex1_spec.rb
spec/subs/subex2/aaa
spec/subs/subex3/s3_spec.rb
spec/subs/subex4/s4.rb
spec/subs/subex4/bbb
那么我应该得到:
_seded/ex2_spec.rb
_seded/subs/subex1_spec.rb
_seded/subs/subex3/s3_spec.rb
注意:目录 subex2 和 subex4 应该不是被创建,因为它们是空的。
我试过:
mkdir -p _seded
find . -name '*_spec.rb' | xargs cat |
sed -e '[/pattern/replace code]' > _seded/$file
但出现如下错误:
$ ./convert_should_to_expect.sh
./convert_should_to_expect.sh: line 5: _seded/: Is a directory
xargs: cat: terminated by signal 13
now doing its !!!
sed: couldn't edit _seded/: not a regular file
awk: cmd. line:1: fatal: cannot open file `_seded/' for reading (Is a directory)
mv: `_seded/tmp' and `_seded/tmp' are the same file
sed: couldn't edit _seded/: not a regular file
sed: couldn't edit _seded/: not a regular file
答案1
你可以这样做:
cd spec
find . -type f -name '*_spec.rb' | while read file; do
mkdir -p ../_seded/"${file%/*}"
cat "$file" | sed ... > ../_seded/"$file"
done
${file%/*}
将切断 的文件名部分$file
,以便它可以用于在中创建输出目录mkdir command
答案2
这是未经测试的代码!这里的想法是给你我认为你应该遵循的逻辑。这不包括子目录,但至少它不会像示例代码那样创建很多空文件,并且它有一些语法更正。
可以使用 grep 或 find 语句之类的东西来改进 for 循环以包含子目录,但我需要一些时间才能弄清楚这一点。也许有人知道他们的头脑?
mkdir -p _seded
TMPFILE=/var/tmp/sedtmp$$$ # Someone can help me with the syntax for a unique file here.
for file in *_spec.rb
do
cat $file
... a bunch of seds >> $TMPFILE # Each with this addition after it.
COUNT=`wc -l $TMPFILE`
if [ COUNT -gt 0 ]
then
cp $TMPFILE _seded/$file
fi
> $TMPFILE
done
rm $TMPFILE