将 .txt 文件转换为带有 bash 标题的 .csv

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16987474/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 23:49:10  来源:igfitidea点击:

Convert .txt file to .csv with header in bash

bashshellcsv

提问by JustTheAverageGirl

.txt looks like:

.txt 看起来像:

2013-04-10;248179;5431;5375.30;1.49
..
..
..

I need a .csv file with a Header:

我需要一个带有标题的 .csv 文件:

Date       Visit   Login  Euro      Rate
2013-04-10 248179  5431   5375.30  1.49
..         ..      ..     ..        ..
..         ..      ..     ..        ..

Is there a way to get this result with BASH?

有没有办法用 BASH 得到这个结果?

回答by alexis

This should do it, ifyour fields don't contain any funny business:

如果您的字段不包含任何有趣的业务,应该这样做:

(echo "Date;Visit;Login;Euro;Rate" ; cat file.txt) | sed 's/;/<tab>/g' > file.csv

You'll just have to type a tab literally in bash (^V TAB). If your version of sed supports it, you can write\tinstead of a literal tab.

您只需要在 bash (^V TAB) 中逐字键入一个选项卡。如果您的 sed 版本支持它,您可以编写\t而不是文字选项卡。

回答by bendaizer

You can use awk :

您可以使用 awk :

echo -e "Data\tVisit\tLogin\tEuro\tRate" > newfile; awk -F';' ' {=}1' OFS="\t" file >> newfile

The {$1=$1}1is a trick to force the new field separator.

{$1=$1}1是强制使用新字段分隔符的技巧。

echowith the -eforces the tab character to be interpreted as a tab.

echo随着-e势力的制表符被解释为一个标签。

Edit : changed pipe | to & and then to ;

编辑:改变管道 | 到 & 然后到 ;

回答by iruvar

This is a pure bash solution.Store the headers in an array and set IFSto taband then echothe header. Loop through the file with read, set IFSto ;on the way in, set IFSto taband run echoon the way out.

这是一个纯 bash 解决方案。将标头存储在一个数组IFStab,然后设置为和echo标头。使用 read 循环遍历文件,设置IFS;on the way in,设置 IFStabecho在退出时运行。

headers=(Date       Visit   Login  Euro      Rate)
((IFS=$'\t'; echo "${headers[*]}"); 
while IFS=';' read -r -a arr; do
(IFS=$'\t'; echo "${arr[*]}";)
done < test.fil) > test.csv