首页 > 解决方案 > 如何将多个文本文件附加在一起然后拆分它们?

问题描述

我正在尝试将文本文件与文件名一起附加,然后将它们分开。

我已经能够使用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 拆分回原始文件?

标签: bash

解决方案


最简单的可能是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/nullgrep确保它始终获得多个文件名参数是一个老技巧;您当然可以grep -H在任何远程现代系统上使用以获得相同的效果。


推荐阅读