通过shell脚本输出编辑.csv文件

时间:2016-12-06 16:20:04

标签: linux bash shell csv

我有一个脚本,它将.csv文件作为输入并逐行运行

kma210,projects.kma210
kma215,projects.kma215_2
KMA3xx,projects.kma3xx
KMI7,projects.kmi7

以上是.csv文件的示例。我为每一行运行了两种类型的进程(例如:abc_process和xyz_process)。

现在我的要求是,一旦脚本运行一行,输出即成功/失败应打印在第三列(abc_process)和第四列(xyz_process)中的同一文件中。

示例请看这里:

kma210,projects.kma210,success,success
kma215,projects.kma215_2,fail,success
KMA3xx,projects.kma3xx,success,fail
KMI7,projects.kmi7,fail,fail

有人可以建议吗?

1 个答案:

答案 0 :(得分:1)

我认为你想要实现的是这种东西。

从输入文件(input.csv)中,按如下方式使用脚本: -

#!/bin/bash

while IFS=',' read -r col1 col2
do
    # The below two read commands are to process the success/fail status
    # string as you indicated. If you are receiving a string of the below 
    # form, from an external bash command; you need to use process-substitution 
    # as

    # IFS= read -r _ p1Status <<(p1Command)
    # IFS= read -r _ p1Status <<(p2Command)

    IFS= read -r _ p1Status <<<"abc success"
    IFS= read -r _ p2Status <<<"xyz fail"

    # The below printf just prints the output as you need to stdout
    # to create a .csv out of it, append it to a new file as

    # printf "%s,%s,%s,%s\n" "$col1" "$col2" "$p1Status" "$p2Status" >> output.csv

    printf "%s,%s,%s,%s\n" "$col1" "$col2" "$p1Status" "$p2Status"
done<input.csv

上述命令写入stdout,产生输出

kma210,projects.kma210,success,fail
kma215,projects.kma215_2,success,fail
KMA3xx,projects.kma3xx,success,fail
KMI7,projects.kmi7,success,fail

您可以使用>>运算符附加到文件中,并使用我注释掉的行。或者,如果您想要一个文件并替换原始文件。添加一行

mv -v output.csv input.csv 

作为剧本的最后一行。