Sponsored Content
Full Discussion: How to join multiple files?
Top Forums Shell Programming and Scripting How to join multiple files? Post 302407064 by durden_tyler on Wednesday 24th of March 2010 12:36:13 PM
Old 03-24-2010
Quote:
Originally Posted by theFinn
... but the problem is that the list of the cities changes from file to file, so they are not in the same order every time. Also this method makes it seem like KLM had temperatures of 5 and 8 on days 1 and 2, when the temps were actually observed on days 2 and 3, which is why I have to have commas in there. The file is a csv, so when i read it into a spreadsheet there will be empty cells at times when a temp was not updated for a particular city.
...
I thought so.
Here's a more elaborate program that should take care of those issues. The script comments should be self-explanatory.

Code:
$
$
$ cat file1.csv
Day 1
City Temp
ABC    20
DEF    30
HIJ     15
$
$ cat file2.csv
Day 2
City  Temp
ABC    22
DEF    29
KLM     5
$
$ cat file3.csv
Day 3
City  Temp
 ABC    24
 DEF    27
 KLM     8
$
$ # show the contents of the Perl program
$ cat -n join_temps.pl
     1  #!perl -w
     2
     3  my $ptrn = "file*.csv";  # the pattern of text files that should be globbed
     4  my $maxday = 1;          # variable to store the maximum day number was encountered
     5  my $day;                 # day number in the current csv file that is being processed
     6  my %temps;               # the hash that stores the temp value for the key "cityNNN"
     7  my %cities;              # the hash to store city names
     8
     9  while (glob $ptrn) {
    10    # open the csv file and process it
    11    open(IN, $_) or die "Can't open file $_: $!";
    12    while (<IN>) {
    13      # trim newline and whitespaces
    14      chomp;
    15      s/^\s*//g;
    16      s/\s*$//g;
    17      # capture the day number as a 3 digit number; set $maxday if needed
    18      # otherwise, set the key=>value pair in the hash %temps
    19      # key = City1NNN, value = temperature; NNN = 3 digit day e.g. 001,098,123 etc.
    20      if (/^Day (\d+)/) {$maxday = $1 if $1 > $maxday; $day = sprintf("%03d",$1)}
    21      elsif (!/^City/) {@x = split/[ ]+/; $cities{$x[0]}=1; $temps{$x[0].$day}=$x[1]}
    22    }
    23    close(IN) or die "Can't close file $_: $!";
    24  }
    25
    26  # now start printing the output data in the form: City<=TAB=>temp1,temp2,temp3,...
    27  foreach $k (sort keys %cities){
    28    print $k,"\t";
    29    foreach $i (1..$maxday) {
    30      $n = sprintf("%03d",$i);
    31      $temp = defined $temps{$k.$n} ? $temps{$k.$n} : "";
    32      # you can code this if your Perl version is 5.10 or higher => $temp = $temps{$k.$n} // "";
    33      print $i == 1 ? $temp : ",$temp";
    34    }
    35    print "\n";
    36  }
$
$ # run the Perl program
$ perl join_temps.pl
ABC     20,22,24
DEF     30,29,27
HIJ     15,,
KLM     ,5,8
$
$
$

HTH,
tyler_durden


NB - You may want to change the tab "\t" at line 28 to comma "," for a proper csv file.

Last edited by durden_tyler; 03-24-2010 at 03:05 PM..
 

10 More Discussions You Might Find Interesting

1. Shell Programming and Scripting

shell script to join multiple files

I am a new to Linux and try to write a script to join three multiple files. For example, there are three files file1 # comment a Kevin b Vin c Sam file 2 # comment a 10 b 20 c 40 file 3 # comment a blue b yellow (7 Replies)
Discussion started by: bonosungho
7 Replies

2. UNIX for Dummies Questions & Answers

Join multiple Split files in Unix

Hi, I have a big file of 50GB size. I need copy it to a second ftp from a ftp. I am not able to do the full 50GB transfer as it timesout after some time. SO i am trying to split the file into 5gb each 10 files with the below command. split -b 5368709120 pack.tar.gz backup.gz After I... (2 Replies)
Discussion started by: venu_nbk
2 Replies

3. UNIX for Dummies Questions & Answers

Join 2 files with multiple columns: awk/grep/join?

Hello, My apologies if this has been posted elsewhere, I have had a look at several threads but I am still confused how to use these functions. I have two files, each with 5 columns: File A: (tab-delimited) PDB CHAIN Start End Fragment 1avq A 171 176 awyfan 1avq A 172 177 wyfany 1c7k A 2 7... (3 Replies)
Discussion started by: InfoSeeker
3 Replies

4. Shell Programming and Scripting

Join multiple files by column with awk

Hi all, I searched through the forum but i can't manage to find a solution. I need to join a set of files placed in a directory (~1600) by column, and obtain an output with first and second column common to each file, but following columns are taken from the file in the list (precisely the fourth... (10 Replies)
Discussion started by: macsx82
10 Replies

5. Shell Programming and Scripting

Awk - join multiple files

Is it possible to join all the files with input1 based on 1st column? input1 a b c d e f input2 a b input3 a e input4 c (2 Replies)
Discussion started by: quincyjones
2 Replies

6. UNIX for Dummies Questions & Answers

How to use the the join command to join multiple files by a common column

Hi, I have 20 tab delimited text files that have a common column (column 1). The files are named GSM1.txt through GSM20.txt. Each file has 3 columns (2 other columns in addition to the first common column). I want to write a script to join the files by the first common column so that in the... (5 Replies)
Discussion started by: evelibertine
5 Replies

7. Shell Programming and Scripting

Join multiple files

Hi there, I am trying to join 24 files (i showed example of 3 files below). They all have 2 columns. The first columns is common to all. The files are tab delimited eg file 1 rs0001 100e-34 rs0003 2.8e-01 rs008 1.9e-90 file 2 rs0001 1.98e-22 rs0004 3.77e-10... (4 Replies)
Discussion started by: fat
4 Replies

8. Shell Programming and Scripting

Join multiple files with filename

Please help, I want to join multiple files based on column 1, and put the missing values as 0. Also the colname in the output should say which file the values came from. FILE1 1 11 2 12 3 13 FILE2 2 22 3 23 4 24 FILE3 1 31 3 33 4 34 FILE1 FILE2 FILE3 1 11 0 31 (1 Reply)
Discussion started by: newbie83
1 Replies

9. Shell Programming and Scripting

Join files on multiple fields

Hello all, I want to join 2 tabbed files on the first 2 fields, and filling the missing values with 0. The 3rd column in each file is constant for the entire file. file1 12658699 ST5 XX2720 0 1 0 1 53039541 ST5 XX2720 1 0 1.5 1 file2 ... (6 Replies)
Discussion started by: sheetalk
6 Replies

10. Shell Programming and Scripting

Join 2nd column of multiple files

Dear All, I have many files formatted like this: file1.txt: 1/2-SBSRNA4 18 A1BG 3 A1BG-AS1 6 A1CF 0 A2LD1 1 A2M 1160 file2.txt 1/2-SBSRNA4 53 A1BG 1 A1BG-AS1 7 A1CF 0 A2LD1 3 A2M 2780 (5 Replies)
Discussion started by: paolo.kunder
5 Replies
csv(n)								  CSV processing							    csv(n)

NAME
csv - Procedures to handle CSV data. SYNOPSIS
package require Tcl 8.3 package require csv ?0.3? ::csv::join values {sepChar ,} ::csv::joinlist values {sepChar ,} ::csv::read2matrix chan m {sepChar ,} {expand none} ::csv::read2queue chan q {sepChar ,} ::csv::report cmd matrix ?chan? ::csv::split line {sepChar ,} ::csv::split2matrix m line {sepChar ,} {expand none} ::csv::split2queue q line {sepChar ,} ::csv::writematrix m chan {sepChar ,} ::csv::writequeue q chan {sepChar ,} DESCRIPTION
The csv package provides commands to manipulate information in CSV FORMAT (CSV = Comma Separated Values). COMMANDS
The following commands are available: ::csv::join values {sepChar ,} 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 ",". ::csv::joinlist values {sepChar ,} 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 ",". Each element of the outer list 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 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 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 line {sepChar ,} 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 ",". ::csv::split2matrix 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 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 ,} 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 ,} 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
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 lan- guages it may be ";" however, although this is not important for this case (The functions provided here allow any separator character). If a value contains itself the separator ",", then it (the value) is put between "". If a value contains ", it is replaced by "". EXAMPLE
The record 123,"123,521.2","Mary says ""Hello, I am Mary""" is parsed as follows: a) 123 b) 123,521.2 c) Mary says "Hello, I am Mary" SEE ALSO
matrix, queue KEYWORDS
csv, matrix, queue, package, tcllib csv 0.3 csv(n)
All times are GMT -4. The time now is 05:58 PM.
Unix & Linux Forums Content Copyright 1993-2022. All Rights Reserved.
Privacy Policy