Reputation: 3
I have a Python script that outputs a text file with thousands of random filenames in a comma separated list, all on a single row.
randomFileName1, randomFileName2, randomFileName3, etc.
I want to take each value in the list and put it into its own row in a new CSV file.
randomFileName1
randomFileName2
randomFileName3
I've tried some variations of awk
with no success. What's the best way to move these values into their own rows?
Upvotes: 0
Views: 415
Reputation: 3
I was actually able to figure this out using the import csv
module in Python. I'm sure this could be cleaned up a bit, but it does what I need it to do.
import csv
with open('parse.txt', 'r') as csv_file:
csv_reader = csv.reader(csv_file)
with open('parse_write.csv', 'w', newline='') as new_file:
csv_writer = csv.writer(new_file, delimiter='\t')
for line in csv_reader:
for file_name in line:
csv_writer.writerow(file_name)
Upvotes: 0
Reputation: 14900
(g)awk:
echo randomFileName1, randomFileName2, randomFileName3 | \
awk '{ split($0,a,/,[ ]*/); for (i in a) { print a[i] }}'
python:
import re
a="randomFileName1, randomFileName2, randomFileName3"
b=re.split(r',[ ]*',a)
for i in b:
print(i)
(inspiration from: String splitting in Python using regex )
Upvotes: 0
Reputation: 4004
With GNU sed
:
sed 's|, |\n|g' file
Or, for a portable alternative,
sed 's|, |\
|g' file
Upvotes: 1