开发者

Making csv from txt files

I have a lot of txt files like this:

Title 1
Text 1(more then 1 line)

And I would 开发者_Python百科like to make one csv file from all of them that it will look like this:

Title 1,Text 1
Title 2,Text 2
Title 3,Text 3
etc

How could I do it? I think that awk is good for it but don't know how to realize it.


May I suggest:

paste -d, file1 file2 file3

To handle large numbers of files, max 40 per output file (untested, but close):

xargs -n40 files... echo >tempfile
num=1
for line in $(<tempfile)
do
    paste -d, $line >outfile.$num
    let num=num+1
done


This is approximately what you posted with some improvements.

for text in *
do
    awk 'BEGIN {q="\""; print q}
         NR==1 {
                gsub(" "," ")    # why?
                gsub("Title: *","")
                print
               }
         NR>1  {
                gsub(" "," ")    # why?
                gsub("Content: *","")
                gsub(q,q q)
                print
               }

         END {print q}' "$text" >> ../final
done

Edit:

If you have a bunch of files that consist of only two lines, try this:

sed 'N;s/\n/,/' file*.txt

If the files contain more than two lines each then it will put each pair of lines on the same line separated by a comma.


Given 3 files containing the following data:

file1.txt

Heading 1
Text 1
Text 2

file2.txt

Heading 2
Text 1

file3.txt

Heading 3
Text 1
text 2
Text 3

The expected results are:

Heading 1,Text 1,Text 2 
Heading 2,Text1 
Heading 3,Text 1,text 2,Text 3

This is accomplished using the program createcsv.awk below invoked as

gawk -f createcsv.awk file1.txt file2.txt file3.txt

createcsv.awk

{
  if (1 == FNR) {
     # It is the first line of a new file
     if (csvline != "") {
       # First file or empty files we can ignore
       print csvline;
     }
     csvline = "";
     delimiter = "";
  }
  csvline = csvline delimiter $0;
  if ("" == delimiter) { delimiter="," }
}
END{
 print csvline;
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜