如何在bash中修改csv的列

时间:2017-12-18 15:23:27

标签: bash csv

编辑,这是我按照建议修改完整文件的方式。 它仍未按预期工作:第4列在stdout中打印为空值,myCSV.csv未被应用函数更改:

#!/bin/bash

function dec2ip() {
   local ip dec=$@
   for e in {3..0}
      do
         ((octet = dec / (256 ** e) ))
         ((dec -= octet * 256 ** e))
         ip+=$delim$octet
         local delim=.
      done
# printf '%s\n' "$ip"
}
dec2ip "$@"


decimal_subnets=( $(cut -d ',' -f4 /test/myCSV.csv ) )

echo ${#decimal_subnets[@]}

(
# print the header untouched
read line; echo "$line"
IFS=,
while read -ra fields; do
    fields[3]=$(dec2ip "${fields[3]}")
    echo "${fields[*]}" >> /test/myCSV_dotted.csv
done
) < /test/myCSV.csv

我在命令行看到的输出和myCSV_dotted.csv中显示的相同内容(基本上,第4列是&#34;缺少&#34;):

VLAN ID,NAME,DESCRIPTION,SUBNET
11,txt1,txt2,
12,txt3,txt4,
13,txt5,txt6,

示例输入是:

VLAN ID,NAME,DESCRIPTION,SUBNET 
11,txt1,txt2,123456
12,txt3,txt4,789012
13,txt5,txt6,345678

似乎函数dec2ip()没有提供正确的结果:我缺少什么?

2 个答案:

答案 0 :(得分:1)

( 
    # print the header untouched
    read line; echo "$line"
    IFS=,
    while read -ra fields; do 
        fields[3]=$(dec2ip "${fields[3]}")
        echo "${fields[*]}"
    done 
) < myCSV.csv

输出

VLAN ID,NAME,DESCRIPTION,SUBNET
11,txt1,txt2,0.1.226.64
12,txt3,txt4,0.12.10.20
13,txt5,txt6,0.5.70.78

不要忘记在dec2ip函数中使delim为local {/ p>

答案 1 :(得分:0)

这是有效代码的版本,myCSV_new.csv输出文件正确修改了第4列:

dec2ip () {
local ip dec=$@
   for e in {3..0}
      do
         ((octet = dec / (256 ** e) ))
         ((dec -= octet * 256 ** e))
         ip+=$delim$octet
         local delim=.
      done
printf '%s\n' "$ip"
}

(
    # print the header untouched
    read line; echo "$line" >> /test/myCSV_new.csv
    IFS=,
    while read -ra fields; do
       fields[3]=$(dec2ip "${fields[3]}")
       echo "${fields[*]}" >> /test/myCSV_new.csv
    done
) < /test/myCSV.csv