简体   繁体   中英

Convert .txt file to .csv with header in bash

.txt looks like:

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

I need a .csv file with a Header:

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

Is there a way to get this result with 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). If your version of sed supports it, you can write \\t instead of a literal tab.

You can use 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.

echo with the -e forces the tab character to be interpreted as a tab.

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. Loop through the file with read, set IFS to ; on the way in, set IFS to tab and run echo on the way out.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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