如何在 csv 文件的行之间以及开始和结束位置添加新行

如何在 csv 文件的行之间以及开始和结束位置添加新行

以下输入数据包含带有标题信息的表属性。下面给出了预期的输出以及带有预期文本的标题和换行符。当表名称发生更改时,这是预期的。

输入数据

Table,Host,Database,Schema,column
DEPT,My Host,My Database,Integration,Deptno
EMP,My Host,My Database,stage,emp_no
EMP,My Host,My Database,stage,emp_name

预期输出:

+++ Database Column - begin ++
Table,Host,Database,Schema,column
DEPT,My Host,My Database,Integration,Deptno
+++ Database Column - end +++
+++ Database Column - begin ++
Table,Host,Database,Schema,column
EMP,My Host,My Database,stage,emp_no
EMP,My Host,My Database,stage,emp_name
+++ Database Column - end +++

答案1

也许是这样的:

awk -F, '
  BEGIN {
    table = 1#st field
    begin = "+++ Database Column - begin +++"
    end = "+++ Database Column - end +++"
  }
  NR == 1 {begin = begin "\n" $0; next}
  $table != last_table {
    if (NR > 2) print end
    print begin
    last_table = $table
  }
  {print}
  END{if (NR > 1) print end}'

答案2

这是一种方法:

$ perl -ne 'BEGIN{
                $header="+++ Database Column - begin +++"; 
                $footer="+++ Database Column - end +++";
            }
            if($.==1){
                $header.="\n$_"; 
                next;
            } 
            print "$header$_$footer\n"' file 
+++ Database Column - begin +++
Name,Host,Database,Schema,Table,Description,ODBC Type,Data Type,Native Type
Deptno,My Host,My Database,Integration,Dept,Description of Column,INTEGER,INT16,Number
+++ Database Column - end +++
+++ Database Column - begin +++
Name,Host,Database,Schema,Table,Description,ODBC Type,Data Type,Native Type
empno,My Host,My Database,stage,emp,Description of Column,INTEGER,INT16,Number
+++ Database Column - end +++
+++ Database Column - begin +++
Name,Host,Database,Schema,Table,Description,ODBC Type,Data Type,Native Type
empname,My Host,stage,emp,Description of Column,VARCHAR,STRING,Text
+++ Database Column - end +++

相关内容