遍历文件('for file in ...),还包括子目录?

迈克尔·杜兰特

我正在使用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
迈克尔·苏曼(Michael Suelmann)

您可以执行以下操作:

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

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

计算目录(包括子目录)中文件数量的最快方法

如何使用通过FTP的骆驼路由将所有文件从目录(包括子目录)移动到特定目录,而目标中没有子目录?

Shell:按文件计数顺序列出目录(包括子目录)

遍历目录中的子目录

遍历子目录以采样文件

提取zip中的特定文件(包括子目录)

Python:遍历目录和子目录

递归计算目录中的所有文件(包括子目录中的文件)

Bash:遍历目录和子目录(包括隐藏文件)的正确方法是什么?

如何排除所有子目录,但在rsync中包括目录文件?

如何建立目录中所有文件的索引,包括子目录和ZIP文件的内容?

列出目录(包括子目录)以及文件数和累积大小

循环遍历子目录中的json文件

获取指定目录内的文件夹数(也包括子目录)

Bash脚本遍历子目录并写入文件

如何列出Zip存档中的所有* .doc文件,包括子目录中的文件?

遍历子目录并对某些文件执行awk脚本

如何使用Shell脚本备份目录和文件,包括所有子目录和文件?

如何在目录(包括子目录)中查找最新文件?

遍历目录并压缩某些子目录

如何遍历目录中的子目录并计算python中子目录中的文件

如何遍历所有子目录中的文件?

Bash - 循环子目录也包括文件

获取当前目录中文件的总大小(不包括子目录的大小)

子目录中的文件?

使用pathlib根据file.name将文件从子目录复制到其他子目录

如何遍历子目录中的文件?

计算所有不可删除文件的总大小(包括子目录中的文件)

遍历子目录并执行