2010-04-14 40 views
0

我有一个文件,每行有n个数字。该行的第一列是日期:例如12/31/2009。但是,有些日期可能会丢失。我想创建与日期相对应的文件,其中包含后面的数字。例如:如何迭代日期和数据并生成新文件

主文件将包含此数据:

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

生成的文件应该被命名,并具有以下数据,注意格式:

file1.20081228

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

file1.20081231

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

感谢

回答

1
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 
0

如果由于某种原因在乎它是一个bash脚本(而不是awk中,像ghostdog的答案,这是伟大的):

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

或'd = $ {域[0 ]};输出=“file1。$ {d:6:4} $ {d:0:2} $ {d:3:2}”'和'((i ++))'和'INPUT_FILE = $ {1:-inputfile} '(for循环中的切片很聪明,顺便说一句!) – 2010-04-14 23:19:30

+0

也更好用'while read -r line' – ghostdog74 2010-04-14 23:32:32

+0

@ ghostdog74:真的,谢谢。 @丹尼斯威廉姆森:'((i ++))'绝对。处理日期是真的,但我认为有时日期格式有点偏离,'日期'会以这种方式捡起松弛。 – Cascabel 2010-04-15 06:15:31

相关问题