将 .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
Convert .txt file to .csv with header in bash
提问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\t
instead 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}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.
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 IFS
to tab
and then echo
the header. Loop through the file with read, set IFS
to ;
on the way in, set
IFS
to tab
and run echo
on the way out.
这是一个纯 bash 解决方案。将标头存储在一个数组IFS
中tab
,然后设置为和echo
标头。使用 read 循环遍历文件,设置IFS
为;
on the way in,设置
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