在以下目录结构中:
directory1中
-subdirectoryA
--- fileA.txt
-subdirectoryB
--- fileB.txt
subdirectoryC
--- fileC.txt
我想生成一个包含以下串联文本的文本文件:
subdirectoryA的名字
-文本包含fileA.txt内
subdirectoryB的名称
包含fileB.txt内-text
subdirectoryC的名字
-文本包含在fileC.txt
我能够使用以下命令来获取串联的文本文件的内容,但是信息我需要目录名称来组织输出:
find ./prefix_common_to_all_target_directories* -name "*.txt" -exec cat '{}' \; > concatenated_extracted_info.txt
#!/bin/bash
while read mydir; do
echo "${mydir}:" >> output.txt
cat $mydir/*.txt >> output.txt
done < <(find test* -type d )
这将遍历其中的所有目录directory1
,并完全满足您的要求。请注意,您必须在中运行此脚本directory1
。
一些解释:
第一次find test* -type d
运行,每行打印每个子目录的名称。然后将此输出馈送给每行read mydir
运行while
一次循环中的所有内容($mydir
分配给每行(又名子目录名称))。
然后,循环中的第一行将目录名称写入一个冒号output.txt
,后跟一个冒号,使用>>
表示“附加到文件”(如果文件不存在,则会创建该文件)。
循环中的第二行再次*.txt
将子目录中每个文件的内容写入output.txt
“追加模式”。
我的测试设置(上面的脚本另存为createfile.sh
):
$ ls *
test1:
fileA.txt
test2:
fileB.txt
test3:
fileC.txt
$ bash createfile.sh
$ cat output.txt
test1:
file content from dir1
test2:
test content from dir2
test3:
test content from dir3
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句