合并CSV文件:添加而不是合并

use*_*834 18 unix csv bash shell merge

所以基本上我想合并几个CSV文件.我使用以下脚本来做到这一点:

paste -d , *.csv > final.txt
Run Code Online (Sandbox Code Playgroud)

然而,这在过去对我有用,但这次它不起作用.它将数据彼此相邻,而不是彼此相邻.例如,两个文件包含以下格式的记录

CreatedAt   ID
Mon Jul 07 20:43:47 +0000 2014  4.86249E+17
Mon Jul 07 19:58:29 +0000 2014  4.86238E+17
Mon Jul 07 19:42:33 +0000 2014  4.86234E+17
Run Code Online (Sandbox Code Playgroud)

合并后给出

CreatedAt   ID CreatedAt    ID
Mon Jul 07 20:43:47 +0000 2014  4.86249E+17 Mon Jul 07 18:25:53 +0000 2014  4.86215E+17
Mon Jul 07 19:58:29 +0000 2014  4.86238E+17 Mon Jul 07 17:19:18 +0000 2014  4.86198E+17
Mon Jul 07 19:42:33 +0000 2014  4.86234E+17 Mon Jul 07 15:45:13 +0000 2014  4.86174E+17
                                            Mon Jul 07 15:34:13 +0000 2014  4.86176E+17
Run Code Online (Sandbox Code Playgroud)

有谁知道这背后的原因是什么?或者我可以做些什么来强制合并到记录下面?

Has*_*tur 42

假设所有的CSV文件具有相同的格式,并全部以相同的标题,您可以按以下写一个小脚本中的所有文件添加只有一个,并只参加一次头.

#!/bin/bash
OutFileName="X.csv"                       # Fix the output name
i=0                                       # Reset a counter
for filename in ./*.csv; do 
 if [ "$filename"  != "$OutFileName" ] ;      # Avoid recursion 
 then 
   if [[ $i -eq 0 ]] ; then 
      head -1  "$filename" >   "$OutFileName" # Copy header if it is the first file
   fi
   tail -n +2  "$filename" >>  "$OutFileName" # Append from the 2nd line each file
   i=$(( $i + 1 ))                            # Increase the counter
 fi
done
Run Code Online (Sandbox Code Playgroud)

笔记:

  • head -1head -n 1命令打印文件(头)的第一行.
  • 所述tail -n +2一个文件的尾部从所述线开始打印号2( +2)
  • Test [ ... ]用于从输入列表中排除输出文件.
  • 输出文件被改写各一次.
  • 该命令cat a.csv b.csv > X.csv可以简单地用于将a.csv和b csv附加到单个文件中(但是您将标头复制2次).

paste命令将文件粘贴到另一侧的一侧.如果文件的空格为行,则可以获得上面报告的输出.
使用-d ,asks来paste command定义用逗号分隔的字段,,但是上面报告的文件格式不是这种情况.

cat命令改为在标准输出上连接文件和打印,这意味着它将一个文件写入另一个文件.

请参阅man headman tail了解单个选项的语法(某些版本允许head -1其他选项head -n 1)...