我有一个 txt 文件,其中有制表符或空格分隔符。我需要将其转换为 csv。您建议如何使用命令行进行转换?
$ perl -F"//" -nlae 'for (@F) {$a{$_}++};for (keys %a){print $_ if ($a{$_}+1==5 && !($_=~/\w/))};undef %a' moth_gt.txt
上述命令没有输出任何内容。
该文件如下所示:
$ head -10 moth_gt.txt
1.0000 494.5551 234.2510 711.6219 274.2668 481.7198 299.5598 311.0864 339.5756
2.0000 494.6552 233.6892 698.5310 237.2043 478.3979 300.0367 285.5068 300.0367
3.0000 496.0657 234.5680 660.4773 182.6485 477.8938 299.0346 279.7346 239.3273
4.0000 498.0948 236.4126 618.2942 142.6347 477.2553 302.2803 298.6309 175.0104
5.0000 499.2109 237.2335 603.7807 120.0112 473.9058 307.5669 323.1914 136.0130
6.0000 497.2581 236.8611 616.7132 115.5453 473.4415 309.7994 336.1240 123.7323
7.0000 497.2588 237.2343 642.7633 126.7104 471.5815 313.1497 329.7984 132.6645
8.0000 499.1200 239.4676 669.9296 159.0866 470.0935 315.7552 312.3086 156.4817
9.0000 498.0675 237.7640 703.4297 201.8367 468.7934 317.1588 292.7054 184.0948
10.0000 498.9722 237.7636 718.0843 248.8523 469.6981 316.7149 282.5214 219.1346
使用以下命令也无济于事:
$ cat moth_gt.csv | tr "\\t" "," > moth_comma.csv
答案1
awk 中的默认字段分隔符是任何空格 - 因此您不必担心它是空格还是制表符:
awk '{$1=$1} 1' OFS=, moth_gt.txt
或(更详细地)
awk 'BEGIN{OFS=","} {$1=$1; print}' moth_gt.txt
同样在 perl 中:
perl -alne 'print join ",", @F' moth_gt.txt