bash - 如何将多个文本文件附加在一起然后拆分它们?
问题描述
我正在尝试将文本文件与文件名一起附加,然后将它们分开。
我已经能够使用tail将文件附加在一起,但不确定这是否是最好的方法。
MacBook-Pro:test torn$ ls
file1 file2 file3 file4
MacBook-Pro:test torn$ cat *
this is file 1
this is file 2
this is file 3
this is file 4
MacBook-Pro:test torn$ tail -n +1 * > allFiles
MacBook-Pro:test torn$ cat allFiles
==> file1 <==
this is file 1
==> file2 <==
this is file 2
==> file3 <==
this is file 3
==> file4 <==
this is file 4
MacBook-Pro:test torn$
如何将 allFiles 拆分回原始文件?
解决方案
最简单的可能是grep
,因为它将文件名添加到每一行。
bash$ grep ^ one two three /dev/null
one:first line
one:
one:^ empty line
two:
three:^ look, two only contained one empty line
three:this one contains three lines, too
three:quod erat demonstrandum.
使用 Awk 将它们拆分出来是一项微不足道的任务:
awk -F : '$1 != p { if(p) close(p) }
{ print substr($0,length($1)+1 >$1
p=$1 }' combined.txt
添加参数/dev/null
以grep
确保它始终获得多个文件名参数是一个老技巧;您当然可以grep -H
在任何远程现代系统上使用以获得相同的效果。
推荐阅读
- javascript - Cant get firebase to stop overriding old pictures when I upload them in javascript/jquery
- python - 访问python列表循环中的第二个值
- python - 如何以 ~C 速度排空/耗尽异步发电机?
- php - webpack encore symfony4 中的引导程序和 jquery
- uml - 我应该使用 UML 跟踪还是实现
- go - 在一片处理程序中注册一个 http URL 处理程序
- c# - 当 JavaScript 被缩小时,捆绑会产生冲突
- azure-data-explorer - 如何编写 Kusto 查询以在一张表中获取结果?
- angular - 角度应用程序上的多个根模块
- flutter - 刷新按钮的正确实现