如果您决定继续使用 bash,这里有一个脚本将为您执行错误检查
#!/usr/bin/env bash
function Error() { 1>&2 echo "$@"; }
function cleanup_csv() {
IFS=$',\r' read -a Header || { Error "could not read header"; return 1; }
IFS=$',\r' read -a Units || { Error "could not read units"; return 1; }
declare -r NCols=${#Header[@]}
declare -r n_units=${#Units[@]}
[[ $NCols -eq $n_units ]] || {
Error "number of columns in Header ($NCols) not equal to Units ($n_units)"
return 1
}
if IFS=$' \t\r' read -a words; then
if [[ $(echo "${words[*]}") ]]; then
Error "expected empty line, read '${words[*]}'"
return 1
fi
else
Error "could not read line 3, expected empty line"
return 1
fi
local i= sep=
for ((i=0; i<NCols; ++i)); do
printf "%s" "$sep${Header[i]} ${Units[i]}"
sep=,
done
printf "\n"
cat
}
cleanup_csv "$@"
给定一个包含您的示例输入的文件
Time,Channel A
(s),(V)
0.00000000,0.58058560
0.00666667,0.58913630
0.01333334,0.58058560
并像这样调用
./cleanup_csv.sh < in
它产生所需的输出
Time (s),Channel A (V)
0.00000000,0.58058560
0.00666667,0.58913630
0.01333334,0.58058560
我还测试了两列以上
Time,Channel A,Channel B
(s),(V),(mV)
0.00000000,0.58058560,12.34
0.00666667,0.58913630,3.1415
0.02000002,0.58058560,0.913
这也很有效
Time (s),Channel A (V),Channel B (mV)
0.00000000,0.58058560,12.34
0.00666667,0.58913630,3.1415
0.02000002,0.58058560,0.913
编辑:
我更新了空行的读取和检测,因为您的输入具有 Windows 样式的行尾 (CRLF)。您可以使用od -xc 查看回车。我继续在字符集中添加制表符以用作字段分隔符 (IFS),然后查看echo 之后是否有任何非空白字符。
这是我测试的输入的十六进制转储(在“空”行中添加了空格和制表符):
$ od -xc in.csv
0000000 6954 656d 432c 6168 6e6e 6c65 4120 0a0d
T i m e , C h a n n e l A \r \n
0000020 7328 2c29 5628 0d29 200a 2009 0d20 300a
( s ) , ( V ) \r \n \t \r \n 0
0000040 302e 3030 3030 3030 2c30 2e30 3835 3530
. 0 0 0 0 0 0 0 0 , 0 . 5 8 0 5
0000060 3538 3036 0a0d 2e30 3030 3636 3636 3736
8 5 6 0 \r \n 0 . 0 0 6 6 6 6 6 7
0000100 302c 352e 3938 3331 3336 0d30 300a 302e
, 0 . 5 8 9 1 3 6 3 0 \r \n 0 . 0
0000120 3331 3333 3333 2c34 2e30 3835 3530 3538
1 3 3 3 3 3 4 , 0 . 5 8 0 5 8 5
0000140 3036 0a0d 2e30 3230 3030 3030 3230 302c
6 0 \r \n 0 . 0 2 0 0 0 0 0 2 , 0
0000160 352e 3038 3835 3635 0d30 300a 302e 3632
. 5 8 0 5 8 5 6 0 \r \n 0 . 0 2 6
0000200 3636 3636 2c39 2e30 3835 3139 3633 3033
6 6 6 6 9 , 0 . 5 8 9 1 3 6 3 0
0000220 0a0d 2e30 3330 3333 3333 3633 302c 352e
\r \n 0 . 0 3 3 3 3 3 3 6 , 0 . 5
0000240 3938 3331 3336 0d30 300a 302e 3034 3030
8 9 1 3 6 3 0 \r \n 0 . 0 4 0 0 0
0000260 3030 2c33 2e30 3835 3139 3633 3033 0a0d
0 0 3 , 0 . 5 8 9 1 3 6 3 0 \r \n
0000300