【问题标题】:Cat several files into one file with the file name before the data将多个文件合并为一个文件,文件名在数据之前
【发布时间】:2016-01-31 07:57:49
【问题描述】:

我有几个包含数据的日志文件。我想要做的是将所有这些文件集中到一个文件中。但在数据进入之前,我希望文件名没有扩展名。例如: 我有的文件:

file1.log file2.log file3.log

我想要的文件:all.log

all.log 包含在其中:

file1
    file1's data
file2
    file2's data
file3
    file3's data

【问题讨论】:

    标签: linux awk find cat


    【解决方案1】:

    使用 awk

    awk 'FNR==1{sub(/[.][^.]*$/, "", FILENAME); print FILENAME} 1' file*.log >all.log
    

    FNR是文件记录号。每个文件的开头都是一个。因此,测试FNR==1 告诉我们我们是否在文件的开头。如果是,那么我们使用 sub(/[.][^.]*$/, "", FILENAME) 从文件名中删除扩展名,然后打印它。

    程序中最后的 1 是 awk 的神秘方式 print-this-line。

    重定向>all.log将所有输出保存在文件all.log中。

    使用外壳

    for f in file*.log; do echo "${f%.*}"; cat "$f"; done >all.log
    

    或者:

    for f in file*.log
    do 
        echo "${f%.*}"
        cat "$f"
    done >all.log
    

    在 shell 中,for f in file*.log; do 开始循环遍历与 glob file*.log 匹配的所有文件。语句echo "${f%.*}" 打印文件名减去扩展名。 ${f%.*}后缀删除 的示例。 cat "$f" 打印文件的内容。 done >all.log 终止循环并将所有输出保存在all.log 中。

    即使文件名包含空格、制表符、换行符或其他难读字符,此循环也能正常工作。

    【讨论】:

    • 感谢一百万!使用 awk 有效!我刚刚执行了您的 awk 命令,例如: awk 'FNR==1{sub(/[.][^.]*$/, "", FILENAME); print FILENAME} 1' file*.log > all.log 并且有效!
    • @SpencerMichealBell 很高兴它成功了。 awk 是一个非常灵活的工具。
    【解决方案2】:
    for i in `ls file*`; do `echo $i | awk -F"." '{print $1}' >> all.log; cat $i >> all.log`; done
    

    【讨论】:

      【解决方案3】:

      假设你有两个文件:

      富:

      a
      b
      c
      

      酒吧:

      d
      e
      f
      

      使用 Perl:

      perl -lpe 'print $ARGV if $. == 1; close(ARGV) if eof' foo bar > all.log

      foo
      a
      b
      c
      bar
      d
      e
      f
      

      $. 是行号
      $ARGV 是当前文件的名称
      close(ARGV) if eof 重置每个文件末尾的行号

      使用 grep:

      grep '' foo bar > all.log

      foo:a
      foo:b
      foo:c
      bar:d
      bar:e
      bar:f
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-08-17
        • 2021-11-08
        • 1970-01-01
        • 2012-02-10
        • 2021-05-28
        • 2014-11-06
        相关资源
        最近更新 更多