将多个文件附加到单个输出文件,但文件之间有消息

Appending multiple files to single output file but w/ message between the files

我想将名为 lab_X.txt 的多个文件附加到一个输出文件 final.txt。知道一个文件夹中的所有文件都是我需要的文件,我将它们移动到当前目录并使用 cat *.txt > final.txt,知道 > 覆盖文件。我想在文件之间插入一个类似于 ============= 的简单消息,可以吗?

假设你有 Gnu awk:

awk 'BEGINFILE{print "============="}1' lab*.txt > final.txt

BEGINFILE special pattern(一个 gawk 扩展)在每个文件的第一行之前触发。它定义了变量 FILENAME,以防您想在分隔行中包含名称。

末尾的1是一个永远正确的模式。由于它没有任何操作,因此执行默认操作,打印该行。

这也会打印开头的行。如果你真的不想这样,你可以添加一个支票:

awk 'BEGINFILE{if(nfiles++)print "============="}1' lab*.txt > final.txt

nfiles没有什么特别的。与任何其他 awk 变量一样,它被有效地初始化为 0,并且后缀 ++ 递增它,但仅在返回其值之后。

使用 gnu sed

sed -ns '1s/.*/=============\n&/;w final.txt' lab*.txt

'-s' '--separate'
By default, 'sed' will consider the files specified on the command line as a single continuous long stream. This GNU 'sed' extension allows the user to consider them as separate files: range addresses (such as '/abc/,/def/') are not allowed to span several files, line numbers are relative to the start of each file, '$' refers to the last line of each file, and files invoked from the 'R' commands are rewound at the start of each file.