2017-02-20 9 views
2

ich eine CSV-Datei des Formulars haben:Splitting CSV-Datei in Textdateien

1,frog 
2,truck 
3,truck 
4,deer 
5,automobile 

und so weiter, für etwa 50 000 Einträge. Ich mag 50 000 getrennte TXT-Dateien mit der Zahl vor dem Komma und mit dem Wort nach dem Komma, wie so genannt, erstellen:

1.txt contains: frog 
2.txt contains: truck 
3.txt contains: truck 
4.txt contains: deer 
5.txt contains: automobile 

und so weiter.

Dies ist das Skript, das ich bisher geschrieben habe, aber es nicht richtig funktioniert:

#!/bin/bash 

folder=/home/data/cifar10 

for file in $(find "$folder" -type f -iname "*.csv") 
do 
    name=$(basename "$file" .txt) 

while read -r tag line; do 
    printf '%s\n' "$line" >"$tag".txt 
done <"$file" 
rm "$file" 

done 

Antwort

3

Das Problem in Ihrer inneren Schleife ist:

while read -r tag line; do 
    printf '%s\n' "$line" > "$tag".txt 
done < "$file" 

Sie müssen IFS einstellen zu , so dass Tag und Zeile korrekt analysiert:

while IFS=, read -r tag line; do 
    printf '%s\n' "$line" > "$tag".txt 
done < "$file" 

Sie 01 verwenden könnenanstelle von find, mit Bash 4.0+. Dies wird zu Wort Spaltung und Globbing immun sein, im Gegensatz zu Normal find:

shopt -s globstar nullglob 
for file in /home/data/cifar10/**/*.csv; do 
    while IFS=, read -r tag line; do 
    printf '%s\n' "$line" > "$tag".txt 
    done < "$file" 
done 

Beachten Sie, dass der Name durch name=$(basename "$file" .txt) Anweisung festgelegt ist in Ihrem Code nicht verwendet werden.

+0

Danke, weiß nicht, wie ich das nicht gesehen haben. – Qubix

1

Ein awk Alternative:

awk -F, '{print $2 > $1 ".txt"}' file.csv 
0
awk 'BEGIN{FS=","} {print $1".txt contains: "$2}' file 

1.txt contains: frog 
2.txt contains: truck 
3.txt contains: truck 
4.txt contains: deer 
5.txt contains: automobile