Making csv from txt files

﹥>﹥吖頭↗ 提交于 2020-01-25 12:17:09

问题


I have a lot of txt files like this:

Title 1
Text 1(more then 1 line)

And I would 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.


回答1:


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



回答2:


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.




回答3:


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;
}


来源:https://stackoverflow.com/questions/4313247/making-csv-from-txt-files

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!