Convert .txt file to .csv with header in bash

后端 未结 3 2014
花落未央
花落未央 2020-12-20 10:08

.txt looks like:

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

I need a .csv file with a Header:

Date       Visit   Login           


        
相关标签:
3条回答
  • 2020-12-20 10:34

    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
    
    0 讨论(0)
  • 2020-12-20 10:38

    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 ;

    0 讨论(0)
  • 2020-12-20 10:43

    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.

    0 讨论(0)
提交回复
热议问题