Bash脚本打印到CSV文件指定的行数

时间:2014-11-21 12:59:58

标签: bash csv scripting

我希望能够将一些变量打印到csv文件中。变量因文件类型而异。并且还应该可以将某些变量作为选项。例如,我设想它运行如下:

./pickafile.sh format1 date time(optional) duration(optional)

给出的例子:

./pickafile.sh watchtv 21112014 150000 10

这将做以下

#!/bin/sh

var1=date (format DDMMYYYY)
time=time (format HHMMSS)
var2=duration (in seconds)
var3='Watchtv'
cheese='Cheddar'
num=20 #number times to print

case $file_type in
    watch_tv)
        cheese='stilton'
for i in 1..$num
do

## print to a csv file each row adding the 
echo $var1,$time+$var2,$var2,$var3,$cheese > $watch_tv.csv
done
        ;;
    watch_ppl)
        echo 'watch ppl??'
        ;;
    watch_animals)
        echo $'wahtc animals?'
        exit 1
        ;;
    *)
        echo "Unknown file- sure it isn't toxic?"
esac

done
exit

所以文件的输出看起来每个时间段增加60秒,持续20次

21112014,150000,10,Watchtv,stilton
21112014,150010,10,Watchtv,stilton
21112014,150020,10,Watchtv,stilton
21112014,150030,10,Watchtv,stilton
21112014,150040,10,Watchtv,stilton
21112014,150050,10,Watchtv,stilton
21112014,150100,10,Watchtv,stilton
etc

1 个答案:

答案 0 :(得分:0)

我将您的伪代码转换为实际代码,纠正了一些粘贴错误。我相信你能够完成剩下的工作。

#!/bin/sh

# $ date; date --date='now +10 Seconds'
# Fri Nov 21 17:28:33 CET 2014
# Fri Nov 21 17:28:43 CET 2014

var1=$(date '+%d%m%Y') # date (format DDMMYYYY)
time=$(date '+%H%M%S') # time (format HHMMSS)
var2=$4 # duration (in seconds)
if [ "" = "$var" ]; then
    var2=10 # default value
fi
# var3='Watchtv'
cheese='Cheddar' # default cheese
num=20 #number times to print

case $file_type in
    watch_tv)
        cheese='stilton'
        ;;
    watch_ppl)
        echo 'watch ppl??'
        ;;
    watch_animals)
        echo $'wahtc animals?'
        exit 1
        ;;
    *)
        echo "Unknown file- sure it isn't toxic?";;
esac

for (( i=1; i<=$num; i++)); do
    offset=$((var2*i)) # calculate the offset
    ## print to a csv file each row adding the
    #echo $var1,$time+$var2,$var2,$var3,$cheese > $watch_tv.csv
    echo "$(date '+%d%m%Y' --date="now +$offset Seconds"),$(date '+%H%M%S' --date="now +$offset Seconds"),$var2,$var3,$cheese"
done

输出:

$ bash script.bash watchtv 21112014 150000 10

Unknown file- sure it isn't toxic?
21112014,174412,10,,Cheddar
21112014,174422,10,,Cheddar
21112014,174432,10,,Cheddar
21112014,174442,10,,Cheddar
21112014,174452,10,,Cheddar
21112014,174502,10,,Cheddar
21112014,174512,10,,Cheddar
21112014,174522,10,,Cheddar
21112014,174532,10,,Cheddar
21112014,174542,10,,Cheddar
21112014,174552,10,,Cheddar
21112014,174602,10,,Cheddar
21112014,174612,10,,Cheddar
21112014,174622,10,,Cheddar
21112014,174633,10,,Cheddar
21112014,174643,10,,Cheddar
21112014,174653,10,,Cheddar
21112014,174703,10,,Cheddar
21112014,174713,10,,Cheddar
21112014,174723,10,,Cheddar