faujong
faujong

Reputation: 1129

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"

Upvotes: 0

Views: 924

Answers (2)

choroba
choroba

Reputation: 241808

#!/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

Upvotes: 3

TheMadTechnician
TheMadTechnician

Reputation: 36287

If you are running powershell you should be able to use the -TotalCount (aliases -Head and -First) parameter of Get-Content (alias GC) to just get the first line of a file.

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

Upvotes: 1

Related Questions