简体   繁体   中英

How to get the header from a CSV file and write it to another file?

How can I get the header from a CSV file and write it to another file ? This code works if I don't have many columns in the CSV file, but it doesn't work when my CSV file contains 200+ columns. It just echoes the column header (but not all of them, they are truncated) to the screen.

@echo off
set /p "header="<book1.csv
echo %header% > "book3.csv"
#!/usr/bin/perl
use warnings;
use strict;

use Text::CSV_XS;

my $csv = 'Text::CSV_XS'->new({binary => 1, escape_char => '\\'});
open my $fh, '<', 'book1.csv' or die $!;
my $h = $csv->getline($fh);

my $out = 'Text::CSV_XS'->new({eol => $/, escape_char => '\\'});
open my $fho, '>', 'book3.csv' or die $!;
$out->say($fho, $h);

Tested with

"Header 1","Header, 2","Header \"3\"","Header
4"
1,2,3,4

如果您正在运行PowerShell中,你应该能够使用-TotalCount (别名-Head-First )的参数Get-Content (别名GC )只得到一个文件的第一行。

gc book1.csv -head 1|sc book3.csv

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM