[英]Cat several files into one file with the file name before the data
I have several log files with data in them. 我有几个带有数据的日志文件。 What i want to do is cat all these files into one file. 我想要做的就是将所有这些文件合并为一个文件。 But before the data goes in i want the file name to be there without the extension. 但是在数据输入之前,我希望文件名不带扩展名。 For Example: Files I have: 例如:我拥有的文件:
file1.log file2.log file3.log
The file that i want: all.log 我想要的文件:all.log
all.log to have in it: all.log包含在其中:
file1
file1's data
file2
file2's data
file3
file3's data
awk 'FNR==1{sub(/[.][^.]*$/, "", FILENAME); print FILENAME} 1' file*.log >all.log
FNR
is the file record number. FNR
是文件记录号。 It is one at the beginning of each file. 它是每个文件开头的一个。 Thus, the test FNR==1
tells us if we are at the beginning of a file. 因此,测试FNR==1
告诉我们是否在文件的开头。 If we are, then we remove the extension from the filename using sub(/[.][^.]*$/, "", FILENAME)
and then we print it. 如果是这样,则使用sub(/[.][^.]*$/, "", FILENAME)
从文件名中删除扩展名,然后进行打印。
The final 1
in the program is awk's cryptic way of saying print-this-line. 程序中的最后1
是awk所说的print-this-line的神秘方式。
The redirection >all.log
saves all the output in file all.log
. 重定向>all.log
将所有输出保存在文件all.log
。
for f in file*.log; do echo "${f%.*}"; cat "$f"; done >all.log
Or: 要么:
for f in file*.log
do
echo "${f%.*}"
cat "$f"
done >all.log
In shell, for f in file*.log; do
在shell中, for f in file*.log; do
for f in file*.log; do
starts a loop over all files matching the glob file*.log
. for f in file*.log; do
在所有与glob file*.log
匹配的file*.log
启动循环。 The statement echo "${f%.*}"
prints the file name minus the extension. 语句echo "${f%.*}"
打印文件名减去扩展名。 ${f%.*}
is an example of suffix removal . ${f%.*}
是删除后缀的示例。 cat "$f"
prints the contents of the file. cat "$f"
打印文件的内容。 done >all.log
terminates the loop and saves all the output in all.log
. done >all.log
终止循环并将所有输出保存在all.log
。
This loop will work correctly even if file names contain spaces, tabs, newlines, or other difficult characters. 即使文件名包含空格,制表符,换行符或其他困难字符,此循环也将正常工作。
Suppose you have two files: 假设您有两个文件:
foo: FOO:
a
b
c
bar: 酒吧:
d
e
f
Using Perl: 使用Perl:
perl -lpe 'print $ARGV if $. == 1; close(ARGV) if eof' foo bar > all.log
foo
a
b
c
bar
d
e
f
$.
is the line number 是行号
$ARGV
is the name of the current file $ARGV
是当前文件的名称
close(ARGV) if eof
resets the line number at the end of each file close(ARGV) if eof
重置每个文件末尾的行号,则close(ARGV) if eof
Using grep: 使用grep:
grep '' foo bar > all.log
foo:a
foo:b
foo:c
bar:d
bar:e
bar:f
for i in `ls file*`; do `echo $i | awk -F"." '{print $1}' >> all.log; cat $i >> all.log`; done
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.