如何使用shell脚本创建csv文件

时间:2016-10-21 11:45:05

标签: bash shell scripting

我的输出目前是:

echo "Time Taken to checkout svn repository repo_performance hosted on $host on `date` is : $Time_checkout seconds" >> log.csv
    echo "Time Taken to add $loopmax 10MB svn files in svn repository repo_performance  hosted on $host `date` is : $Time_add seconds" >> log.csv
    echo "Time Taken to commit $loopmax 10MB svn files in svn repository repo_performance  hosted on $host on `date` is : $Time_commit seconds" >> log.csv

但是,我想创建一个csv文件,其中包含Host,Date,Operation,Duration及其值。

如何使用脚本编写它?

5 个答案:

答案 0 :(得分:4)

你可以尝试这样的事情;

printf "Host\tDate\tOperation\tDuration\n" >> log.csv
printf "$host\t$(date)\tTime Taken to checkout\t$Time_checkout\n" >> log.csv
printf "$host\t$(date)\tTime Taken to add $loopmax 10MB svn files\t$Time_add\n" >> log.csv
printf "$host\t$(date)\tTime Taken to commit $loopmax 10MB svn files\t$Time_commit\n" >> log.csv

答案 1 :(得分:3)

您可以这样做:

echo "$host, `date`, checkout,$Time_checkout" >> log.csv
echo "$host, `date`, add, $Time_add" >> log.csv
echo "$host, `date`, cimmit, $Time_commits" >> log.csv

答案 2 :(得分:1)

以防万一有人正在寻找值在双引号 (") 中的 CSV,您必须删除 echo 的外部引号,并将它们(转义)用于每个值,像这样:

echo \"$host\",\"$date",\"checkout\",\"$checkout_time\" >> log.csv
echo \"$host\",\"$date",\"add\",\"$add_time\" >> log.csv
echo \"$host\",\"$date",\"commit\",\"$commit_time\" >> log.csv

我建议编写一个函数,让您的脚本更简洁、更易于阅读,就像这样。

write_csv(){
    echo \"$1\",\"$2\",\"$3\",\"$4\" >> log.csv
}
write_csv $host $date checkout $checkout_time
write_csv $host $date add $add_time
write_csv $host $date commit $commit_time

答案 3 :(得分:1)

您还可以概括 Mig82 的 answer 以支持像这样的变量参数:

# Usage: csv <items>

csv()
{
    local items=("$@")

    (
    IFS=,
    echo "${items[*]}"
    )
}

csv 1 "2 3" >> log.csv

答案 4 :(得分:0)

使用@Nishant 的答案,稍作调整以处理引用:

    csv()
    {
        local items=("$@")
    
        # quote and escape as needed
        # https://datatracker.ietf.org/doc/html/rfc4180
        for i in "${!items[@]}"
        do
            if [[ "${items[$i]}" =~ [,\"] ]]
            then
                items[$i]=\"$(echo -n "${items[$i]}" | sed s/\"/\"\"/g)\"
            fi
        done
    
        (
        IFS=,
        echo "${items[*]}"
        )
    }