【问题标题】:Fill cells of csv with bash when cellname and value both given in output当单元格名和值都在输出中给出时,用 bash 填充 csv 的单元格
【发布时间】:2016-10-24 13:44:16
【问题描述】:

我有一个 shell 脚本,它现在可以输出信息。输出格式为:

cellname1
cellvalue1
cellname2
cellvalue2
...

棘手的部分是,这个脚本迭代了具有不同单元名的多组数据(总是有一些匹配,有时有一些匹配......)。我也不知道cellname 的所有可能值。 因此脚本应该通过查看单元名称来识别正确的单元并将值放入该单元中。 当单元名称第一次出现时,它应该被添加为一个新列。

样本输出:

cellname1, cellname2, cellname3 # not necessarily needed since i can add them at the end
value1, value2, value3
foo1, foo2, foo3
bar1, bar2, bar3, bar4 # <-- see the new value here

我还是 bash 新手,在这里感谢任何帮助

【问题讨论】:

  • 请显示与示例输出对应的输入,目前还不清楚发生了什么。您如何知道 CSV 中的新行应该开始?
  • 脚本循环遍历数据集,以便知道何时完成一组数据并开始下一组数据

标签: bash csv


【解决方案1】:

诀窍是一次循环遍历两行数据;将值存储到数组中;然后在最后输出一个 csv(如果你愿意,你可以在 if [ -z "$name" ] 块中打印输出,但是你会丢失漂亮的标题)。

#!/bin/bash
declare -A cell
declare -A head

i=0
while read name
do
    if [ -z "$name" ]
    then
        ((i+=1))
    else
        head[$name]=$name
        read value
        cell[$i,$name]=$value;
    fi
done < "${1:-/dev/stdin}"

printf "%-10s; " "${head[@]}"; echo
printf "%.0s----------; " ${head[@]}; echo 

j=0
until [ $j -gt $i ]; do   
    for name in ${head[@]}
    do
        printf "%-10s; " "${cell[$j,$name]}"
    done
    echo
    ((j+=1))
done

上面的脚本假定集合由一个空行分隔,并将返回:

$ head data
head1
value1-1
head2
value2-1

head2
value2-2

$ ./csvgen.sh data
head2     ; head3     ; head1     ; head4     ; 
----------; ----------; ----------; ----------; 
value2-1  ;           ; value1-1  ;           ; 
value2-2  ; value3-2  ;           ;           ; 
value2-3  ;           ; value1-3  ; value4-3  ; 

工作原理:

loop over each line of either a file or stdin。

while read name
do
# ...
done < "${1:-/dev/stdin}"

if [ -z "$name" ] # If the line has a length of zero the set has ended
then              # so increse the set index by 1.
    ((i+=1))
else
    head[$name]=$name  # this array contains all the headers we have seen
    read value  # read the next line to $value
    cell[$i,$name]=$value; # save $value in array indexed by set and header
fi

printf "%-10s; " "${head[@]}";  # print each header from 
echo   # the above wont end the line so echo for a "\n"

printf "%.0s----------; " ${head[@]}; # %.0s truncates the input to nothing  
echo                                  # printing only the '----------'

until [  $j -gt $i ]; do     # for each set index
    for name in ${head[@]}   # loop thru the headers
    do
        printf "%-10s; " "${cell[$j,$name]}" # then print the values
    done
    echo # end each set with "\n"
    ((j+=1))
done

【讨论】:

  • 这正是我正在寻找的。甚至设置的分隔匹配。如果您可以在代码中添加一些 cmets 以便我理解它会很好
  • 没问题,答案已更新。 bash 对文本处理来说并不是那么好,继续前进,您可能需要研究 perl 或 awk 来处理这些类型的工作......
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-01-18
  • 2020-01-30
  • 2022-11-23
  • 1970-01-01
  • 1970-01-01
  • 2013-02-21
相关资源
最近更新 更多