简体   繁体   English

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

[英]Convert .txt file to .csv with header in bash

.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 得到这个结果?

This should do it, if your 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).您只需要在 bash (^V TAB) 中逐字键入一个选项卡。 If your version of sed supports it, you can write \\t instead of a literal tab.如果您的 sed 版本支持它,您可以编写\\t而不是文字制表符。

You can use awk :您可以使用 awk :

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

The {$1=$1}1 is a trick to force the new field separator. {$1=$1}1是强制使用新字段分隔符的技巧。

echo with the -e forces the tab character to be interpreted as a tab.带有-e echo强制将制表符解释为制表符。

Edit : changed pipe |编辑:改变管道 | to & and then to ;到 & 然后到 ;

This is a pure bash solution.Store the headers in an array and set IFS to tab and then echo the header.这是一个纯 bash 解决方案。将标头存储在一个数组中并将IFS设置为tab ,然后echo显标头。 Loop through the file with read, set IFS to ;使用 read 循环遍历文件,将IFS设置为; on the way in, set IFS to tab and run echo on the way out.在进入的途中,将IFS设置为tab并在退出时运行echo

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

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

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