简体   繁体   English

在 shell 中将 .txt 转换为 .csv

[英]Convert .txt to .csv in shell

I have a text file:我有一个文本文件:

ifile.txt
1  4    22.0  3.3 2.3
2  2    34.1  5.4 2.3
3  2    33.0 34.0 2.3
4 12     3.0 43.0 4.4

I would like to convert it to a csv file:我想将其转换为 csv 文件:

ofile.txt
ID,No,A,B,C
1,4,22.0,3.3,2.3
2,2,34.1,5.4,2.3
3,2,33.0,34.0,2.3
4,12,3.0,43.0,4.4

I was trying with this, but not getting the result.我正在尝试这个,但没有得到结果。

(echo "ID,No,A,B,C" ; cat ifile.txt) | sed 's/<space>/<comma>/g' > ofile.csv

Only sed and nothing else只有 sed 而没有别的

sed 's/ \+/,/g' ifile.txt > ofile.csv

cat ofile.csv猫文件.csv

1,4,22.0,3.3,2.3
2,2,34.1,5.4,2.3
3,2,33.0,34.0,2.3
4,12,3.0,43.0,4.4

awk may be a bit of an overkill here. awk在这里可能有点矫枉过正。 IMHO, using tr for straight-forward substitutions like this is much simpler:恕我直言,使用tr进行这样的直接替换要简单得多:

$ cat ifile.txt | tr -s '[:blank:]' ',' > ofile.txt

here is the awk version这是 awk 版本
awk 'BEGIN{print "ID,No,A,B,C"}{print $1","$2","$3","$4","$5}' ifile.txt

output:输出:

ID,No,A,B,C 
1,4,22.0,3.3,2.3 
2,2,34.1,5.4,2.3 
3,2,33.0,34.0,2.3
4,12,3.0,43.0,4.4

Try this ..试试这个..

tr -s " " < ifile.txt | sed 's/ /,/g' > ofile.txt

OUTPUT输出

1,4,22.0,3.3,2.3
2,2,34.1,5.4,2.3
3,2,33.0,34.0,2.3
4,12,3.0,43.0,4.4

One possibility, not necessarily the best, is:一种可能性,不一定是最好的,是:

 sed -e '1i\
 ID,No,A,B,C' -e 's/[[:space:]]\{1,\}/,/g' ifile.txt

Insert the heading before line 1;在第 1 行之前插入标题; change each sequence of one or more space-like characters to a comma.将一个或多个类似空格的字符的每个序列更改为逗号。 The line break is necessary in traditional (POSIX standard — in this case, BSD or Mac OS X) sed ;换行符在传统(POSIX 标准——在这种情况下,BSD 或 Mac OS X) sed是必要的; GNU sed allows you to use: GNU sed允许您使用:

/opt/gnu/bin/sed -e '1i\' -e 'ID,No,A,B,C' -e 's/[[:space:]]\{1,\}/,/g'

Output:输出:

ID,No,A,B,C
1,4,22.0,3.3,2.3
2,2,34.1,5.4,2.3
3,2,33.0,34.0,2.3
4,12,3.0,43.0,4.4

Alternatively, and more simply, have sed deal with the file and use echo to add the header, as you did in outline:或者,更简单的是,使用sed处理文件并使用echo添加标题,就像您在大纲中所做的那样:

{
echo "ID,No,A,B,C"
sed -e 's/[[:space:]]\{1,\}/,/g' ifile.txt
} > ofile.txt

On review, this is probably what I'd use.经过审查,这可能是我会使用的。

Simply do it using awk command .只需使用awk命令即可。

 awk '{
     printf("%d, %d, %.1lf, %.1lf,%.1lf\n", $1,$2,$3,$4,$5); 
 }'  input.txt > output.csv

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM