tags:

views:

31

answers:

2

I have a file, with n numbers on each lines. The first column on the line is a date: say 12/31/2009. However, some dates can be missing. I want to create files corresponding to date, containing the numbers that follow. For example:

master file will contain this data:

  12/28/2009   5 6 7  
  12/31/2009   6 7  7

The resulting files should be named and have the following data, note format:

file1.20081228

  item     data 
 -------   ------    
  1          5
  2          6   
  3          7 

file1.20081231

  item     data 
 -------   ------  
   1         6 
   2         7   
   3         7

Thanks

+1  A: 
awk '
{
  m=split($1,a,"/")
  c=0
  newfile="file."++f"."a[3]a[1]a[2]
  print "item\tdata"  > newfile
  print "----------" > newfile
  for(i=2;i<=NF;i++){
    print "item\t"++c"\t"$i >newfile
  }
}' file
ghostdog74
A: 

If for some reason care about it being a bash script (instead of awk, like ghostdog's answer, which is great):

#!/bin/bash

# use the first argument, or hardcode
# INPUT_FILE=$1
# INPUT_FILE=input_file

while read line; do
    fields=($line)
    output="file1.$(date --date=${fields[0]} +%Y%m%d)"
    echo "$output:"
    echo " item      data" #> $output
    echo "-----    ------" #> $output
    i=1
    for field in "${fields[@]:1}"; do
        printf "%5d     %5d\n" $i $field #> $output
        i=$((i+1))
    done
done < $INPUT_FILE
Jefromi
Or `d=${fields[0]}; output="file1.${d:6:4}${d:0:2}${d:3:2}"` and `(( i++ ))` and `INPUT_FILE=${1:-inputfile}` (The slicing in the `for` loop is clever, by the way!)
Dennis Williamson
also better to use `while read -r line`
ghostdog74
@ghostdog74: True, thanks. @Dennis Williamson: `(( i++ ))` definitely. Processing the date, true, but I figure if the date format's a little off sometimes, `date` will pick up the slack this way.
Jefromi