Bash

如何將目錄中的所有文本文件轉換為一個csv

  • June 30, 2020

我想將目錄中的所有文本文件轉換為一個 csv 文件。我希望 csv 的輸入是由文件名中找到的文本文件的作者標記的文本文件中的文本。作為參考,這是一些文件名的樣子:

'Winston Churchill___The Crisis, Complete.txt'
'Winston Churchill___The Crossing.txt'
'Winston Churchill___The Dwelling Place of Light, Complete.txt'
'Winston Churchill___The Inside of the Cup, Complete.txt'
'Zane Grey___Betty Zane.txt'
'Zane Grey___Desert Gold.txt'
'Zane Grey___Riders of the Purple Sage.txt'

範例輸出為:

column1     column2                     
Author1     text written by author 1......   
Author1     text written by author 1......   
Author2     text written by author 2......   
Author2     text written by author 2......              

編輯:測試文本…. 包含作者在相應列中編寫的 1000 個字元的文本。

Withksh93而不是which 具有對其格式的bash內置列印支持(並且更有效):csv``%#q printf``$(<file)

for file in *___*.txt; do
 printf "%#q,%#q\n" "${file%%___*}" "$(<"$file")"
done >> file.csv

引用自:https://unix.stackexchange.com/questions/595800