1

.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?

2
  • what is the separator on the .csv file? tab? Commented Jun 7, 2013 at 15:17
  • CSV is 'comma separated values'...the delimiter for a CSV file should be a comma. Granted, the layout shown suggests it is a TSV (tab separated values) file. Commented Jun 7, 2013 at 16:01

3 Answers 3

11

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.

Sign up to request clarification or add additional context in comments.

1 Comment

In bash (and other shells that support it), you can use the special quoting $'s/;/\t/g' even if your sed doesn't support \t.
3

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 ;

6 Comments

The pipe does nothing, as all output from echo is directed to the file, and awk is given a file to read from and ignores its standard input.
Yeah you're right, there's nothing to pipe, I meant a "&" of course :p (but it worked anyway)
You don't even need &, since the echo will complete almost immeditely; just use a semicolon.
You know what, I think I rarely used the ; in my entire life. It never crosses my mind -_-' Maybe it's time to change that ...
No need to use the semicolon; just put the two commands on two separate lines. Or use a single redirection with: { echo ...; awk ...; } > newfile where, if you keep it all on one line (as in a comment) you do need both semicolons, but if you spread it out over 4 lines (the braces on a line on their own, with the I/O redirection after the second), then you don't need any semicolons.
|
2

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.