Sponsored Content
Top Forums Shell Programming and Scripting Perl script to modify csv file Post 302829845 by dbashyam on Saturday 6th of July 2013 09:15:06 AM
Old 07-06-2013
Perl script to modify csv file

Hi Friends,

I want to convert a csv file into a ordinary .txt file. I am able to convert but I want the output to look as shown below in the .txt file

Code:
table findhost=
{
{"xyz","abc"},
{"rxz","mmz"},
{"vrr","nnz"},
}
default={"NONE"}

My current perl script

Code:
#!/usr/bin/env perl
use strict;
use warnings;
use Text::CSV;

my @rows;

# Read the CSV file
{
    my $csv = Text::CSV->new()
        or die "Cannot use Text::CSV ($!)";
    my $file = "data.csv";
    open my $fh, '<', $file
        or die "Cannot open $file ($!)";

    while (my $row = $csv->getline($fh))
    {
        push @rows, $row;
    }
    $csv->eof or $csv->error_diag();

    close $fh
        or die "Failed to close $file ($!)";
}

# Munge the data
{
    foreach my $row (@rows)
    {
        foreach my $col (@{$row})
        {
            $col = uc($col);
        }
        print "\n";
    }
}

# Write the data
{
    my $csv = Text::CSV->new()
        or die "Cannot use Text::CSV ($!)";
    my $file = "output.csv";
    open my $fh, '>', $file
        or die "Cannot open $file ($!)";
    $csv->eol("\n");
    foreach my $row (@rows)
    {

        $csv->print($fh, \@{$row})
            or die "Failed to write $file ($!)";
    }
    close $fh
        or die "Failed to close $file ($!)";
}

The output of this script is shown below:

Code:
XYZ,ABC
RXZ,MMZ
VRR,NNZ

I want to make the output to look as shown below:

Code:
table findhost=
{
{"xyz","abc"},
{"rxz","mmz"},
{"vrr","nnz"},
}
default={"NONE"}

My CSV looks as shown below:

Code:
xyz,"abc"
rxz,mmz
vrr,"nnz"

If double quotes are not there in the CSV file I need to ensure that I put the double quotes.

Can anyone tell where I should I modify.

Thanks,
Din
 

10 More Discussions You Might Find Interesting

1. Shell Programming and Scripting

Need help to modify perl script: Text file with line and more than 1 space

Dear Friends, I am beginner in Perl and trying to find the problem in a script. Kindly help me to modify the script. My script is not giving the output for the last field and followed text (LA: Language English). Input file & script as follows: Input file: Thu Mar 19 2:34:14 EDT 2009 STC... (3 Replies)
Discussion started by: srsahu75
3 Replies

2. Shell Programming and Scripting

Simple Script needed for Processing CSV file perl

I am new to perl, and need a script to pull a CSV file, strip out 2 leading columns, and 2 ending columns, and resave the file in a new location. The file is basic and has less than 10,000 records. Secondly, can I schedule perl scripts to run daily? Can someone provide the basic script to... (1 Reply)
Discussion started by: cobbjob
1 Replies

3. Shell Programming and Scripting

Need to modify csv-file with bash script

Hi Guys, I need to write a script, that exports the "moz_places" table of the "places.sqlite"-file (firefox browser history) into a csv-file. That part works. After the export, my csv looks like this: ... 4429;http://www.sqlite.org/sqlite.html;"Command Line Shell For... (11 Replies)
Discussion started by: Sebi0815
11 Replies

4. Shell Programming and Scripting

Please do help: Perl Script to pull out rows from a CSV file

I have CSV file that contains data in the format as shown below: ABC, 67, 56, 67, 78, 89, 76, 55 PDR, 85, 83, 83, 72, 82, 89, 83 MPG, 86, 53, 54, 65, 23, 54, 75 .. .. .. .. I want to create a script that will pull out the rows from the above sheet and paste it into another CSV file.... (12 Replies)
Discussion started by: pankajusc
12 Replies

5. Shell Programming and Scripting

Perl - need script for modify lines

Hello, does somebody can make script for me, which replace: ąćę ąćę ąćę (input file) to ace;|;ąćę ace;|;ąćę ace;|;ąćę (output file) (3 Replies)
Discussion started by: Xadrian
3 Replies

6. Shell Programming and Scripting

Read data from .csv file through shell script & modify

I need to read data from a file called "test.csv" through shell script where the file contains values like name,price,descriptor etc. There are rows where descriptor (& in some rows name) are written as string & other characters like "car_+" OR "bike*" etc where it should contains strings like... (3 Replies)
Discussion started by: raj100
3 Replies

7. Shell Programming and Scripting

Calculate average from CSV file using PERL script

Hi All I have this csv file and I need to calculate the average of FPS. FPS:27.7420, Interval:1314184238772 FPS:25.9798, Interval:1314184242646 FPS:27.4772, Interval:1314184246311 FPS:26.1623, Interval:1314184250159 FPS:26.4515, Interval:1314184253972 FPS:31.5896, Interval:1314184257163... (24 Replies)
Discussion started by: sayachop
24 Replies

8. Shell Programming and Scripting

Calling Pl/sql function in shell script to modify csv

I need to 1.Open a csv 2.Process the csv i.e. Modify 2 column in the csv. To modify the column the value needs to be passed to a pl/sql function and the return value should be updated For eg: If column 2 E,then E will be passed in database function which will return Employee. 3. Write a... (5 Replies)
Discussion started by: Chinky23
5 Replies

9. Shell Programming and Scripting

Perl script to Convert XLSX or XLS files to CSV file

Hi All, I've got in a situation where I need to convert .xlsx or .xls formatted files into simple text file or .csv file. I've found many options but doing this using PERL script is the best way I believe.I'm in AIX box. Perl code should have 2 params while running. i.e perl... (1 Reply)
Discussion started by: manab86
1 Replies

10. Shell Programming and Scripting

Modify CSV file

Hi, I would like to change my CSV file by adding " and : and moving some of the information around. the CSV file looks as follows: 501254424;500440257;PE PACKS;300467279;PREP;;276476070;655031001867176;Two Block;Olga;25/12/2015 00:00:00;Olga I would like to move the field 7 to the front "... (13 Replies)
Discussion started by: omuhans123
13 Replies
csv(n)								  CSV processing							    csv(n)

__________________________________________________________________________________________________________________________________________________

NAME
csv - Procedures to handle CSV data. SYNOPSIS
package require Tcl 8.3 package require csv ?0.7.2? ::csv::iscomplete data ::csv::join values {sepChar ,} {delChar "} ::csv::joinlist values {sepChar ,} {delChar "} ::csv::joinmatrix matrix {sepChar ,} {delChar "} ::csv::read2matrix ?-alternate? chan m {sepChar ,} {expand none} ::csv::read2queue ?-alternate? chan q {sepChar ,} ::csv::report cmd matrix ?chan? ::csv::split ?-alternate? line {sepChar ,} {delChar "} ::csv::split2matrix ?-alternate? m line {sepChar ,} {expand none} ::csv::split2queue ?-alternate? q line {sepChar ,} ::csv::writematrix m chan {sepChar ,} {delChar "} ::csv::writequeue q chan {sepChar ,} {delChar "} _________________________________________________________________ DESCRIPTION
The csv package provides commands to manipulate information in CSV FORMAT (CSV = Comma Separated Values). COMMANDS
The following commands are available: ::csv::iscomplete data A predicate checking if the argument data is a complete csv record. The result is a boolean flag indicating the completeness of the data. The result is true if the data is complete. ::csv::join values {sepChar ,} {delChar "} Takes a list of values and returns a string in CSV format containing these values. The separator character can be defined by the caller, but this is optional. The default is ",". The quoting character can be defined by the caller, but this is optional. The default is '"'. ::csv::joinlist values {sepChar ,} {delChar "} Takes a list of lists of values and returns a string in CSV format containing these values. The separator character can be defined by the caller, but this is optional. The default is ",". The quoting character can be defined by the caller, but this is optional. The default is '"'. Each element of the outer list is considered a record, these are separated by newlines in the result. The ele- ments of each record are formatted as usual (via ::csv::join). ::csv::joinmatrix matrix {sepChar ,} {delChar "} Takes a matrix object following the API specified for the struct::matrix package and returns a string in CSV format containing these values. The separator character can be defined by the caller, but this is optional. The default is ",". The quoting character can be defined by the caller, but this is optional. The default is '"'. Each row of the matrix is considered a record, these are separated by newlines in the result. The elements of each record are formatted as usual (via ::csv::join). ::csv::read2matrix ?-alternate? chan m {sepChar ,} {expand none} A wrapper around ::csv::split2matrix (see below) reading CSV-formatted lines from the specified channel (until EOF) and adding them to the given matrix. For an explanation of the expand argument see ::csv::split2matrix. ::csv::read2queue ?-alternate? chan q {sepChar ,} A wrapper around ::csv::split2queue (see below) reading CSV-formatted lines from the specified channel (until EOF) and adding them to the given queue. ::csv::report cmd matrix ?chan? A report command which can be used by the matrix methods format 2string and format 2chan. For the latter this command delegates the work to ::csv::writematrix. cmd is expected to be either printmatrix or printmatrix2channel. The channel argument, chan, has to be present for the latter and must not be present for the first. ::csv::split ?-alternate? line {sepChar ,} {delChar "} converts a line in CSV format into a list of the values contained in the line. The character used to separate the values from each other can be defined by the caller, via sepChar, but this is optional. The default is ",". The quoting character can be defined by the caller, but this is optional. The default is '"'. If the option -alternate is specified a slightly different syntax is used to parse the input. This syntax is explained below, in the section FORMAT. ::csv::split2matrix ?-alternate? m line {sepChar ,} {expand none} The same as ::csv::split, but appends the resulting list as a new row to the matrix m, using the method add row. The expansion mode specified via expand determines how the command handles a matrix with less columns than contained in line. The allowed modes are: none This is the default mode. In this mode it is the responsibility of the caller to ensure that the matrix has enough columns to contain the full line. If there are not enough columns the list of values is silently truncated at the end to fit. empty In this mode the command expands an empty matrix to hold all columns of the specified line, but goes no further. The overall effect is that the first of a series of lines determines the number of columns in the matrix and all following lines are truncated to that size, as if mode none was set. auto In this mode the command expands the matrix as needed to hold all columns contained in line. The overall effect is that after adding a series of lines the matrix will have enough columns to hold all columns of the longest line encountered so far. ::csv::split2queue ?-alternate? q line {sepChar ,} The same as ::csv::split, but appending the resulting list as a single item to the queue q, using the method put. ::csv::writematrix m chan {sepChar ,} {delChar "} A wrapper around ::csv::join taking all rows in the matrix m and writing them CSV formatted into the channel chan. ::csv::writequeue q chan {sepChar ,} {delChar "} A wrapper around ::csv::join taking all items in the queue q (assumes that they are lists) and writing them CSV formatted into the channel chan. FORMAT
The format of regular CSV files is specified as [1] Each record of a csv file (comma-separated values, as exported e.g. by Excel) is a set of ASCII values separated by ",". For other languages it may be ";" however, although this is not important for this case as the functions provided here allow any separator character. [2] If and only if a value contains itself the separator ",", then it (the value) has to be put between "". If the value does not con- tain the separator character then quoting is optional. [3] If a value contains the character ", that character is represented by "". [4] The output string "" represents the value ". In other words, it is assumed that it was created through rule 3, and only this rule, i.e. that the value was not quoted. An alternate format definition mainly used by MS products specifies that the output string "" is a representation of the empty string. In other words, it is assumed that the output was generated out of the empty string by quoting it (i.e. rule 2), and not through rule 3. This is the only difference between the regular and the alternate format. The alternate format is activated through specification of the option -alternate to the various split commands. EXAMPLE
Using the regular format the record 123,"123,521.2","Mary says ""Hello, I am Mary""","" is parsed into the items a) 123 b) 123,521.2 c) Mary says "Hello, I am Mary" d) (the empty string) Using the alternate format the result is a) 123 b) 123,521.2 c) Mary says "Hello, I am Mary" d) " instead. As can be seen only item (d) is different, now a " instead of the empty string. BUGS, IDEAS, FEEDBACK This document, and the package it describes, will undoubtedly contain bugs and other problems. Please report such in the category csv of the Tcllib SF Trackers [http://sourceforge.net/tracker/?group_id=12883]. Please also report any ideas for enhancements you may have for either package and/or documentation. SEE ALSO
matrix, queue KEYWORDS
csv, matrix, package, queue, tcllib CATEGORY
Text processing COPYRIGHT
Copyright (c) 2002-2009 Andreas Kupries <andreas_kupries@users.sourceforge.net> csv 0.7.2 csv(n)
All times are GMT -4. The time now is 09:12 AM.
Unix & Linux Forums Content Copyright 1993-2022. All Rights Reserved.
Privacy Policy