Linux sort csv file

Sorting a Large CSV File

Large CSV files present a challenge when need arises to sort. Learn how to do that using a database.

“All of life is a constant education.”
― Eleanor Roosevelt, The Wisdom of Eleanor Roosevelt

1. Introduction

Let us explore some ways of sorting large data sets.

By large, I don’t mean typical “big-data” sizes – which might consist of billions of rows. Such data sets fall into the realm of “big data” which we are not exploring today. Instead I am talking of sorting a rather large CSV file – maybe a couple of million rows.

2. The Croaking Excel

First off, I tried the most obvious: loading it into Excel. And promptly received an error the first time.

Second time Excel rebuked me with the following message.

Great job, Excel Developers! You not only can’t open my file, you want to chastise me for attempting a second time. Blah, Blah, Blah! I didn’t even read the wall of text fully. Does you really need so much text to say “Too Large”?

3. Awk and Sort: Linux Command Line

Let’s see. What other methods can I use? How about using the Linux command line? Split the CSV into fields with Awk and use sort.

Out of luck here too.

The CSV includes fields with quotes, line separators and commas. Too complex to use regular expressions with or without Awk.

4. Loading into an ArrayList

Looks like I cannot get it done without programming.

Let us write a Java program to parse the CSV and load the data into a List of Lists. Here is the main loop where the data is being loaded. (It uses the CSV module which handles Byte-Order-Marker, quoted fields, multi-line fields and more.)

Unfortunately that didn’t work too. I got an exception:

Yeah, too big to load it all into memory too. Let us see now, what other options do we have?

5. Load into an SQL Database

Let us load the data into an SQL database. Since I am doing this in Java, the first option that came to my mind was: the H2 database. The H2 database is a nifty piece of software which lets you add SQL capabilities to your application with a single JAR. Let’s roll with it.

The POM segment:

Load the JDBC driver:

The H2 database provides a function CSVREAD() for directly reading a CSV file. From my (limited) experiments, it appears to be able to deal with quoted fields and other complications of CSV.

To write the CSV output after sorting, we use the CSVWRITE() function which can export the output of a query as CSV.

And that did the job. Though the CSV output was somewhat not to my liking; CSVWRITE() enclosed all fields in quotes regardless of whether it was required or not.

It took about 11 minutes (wall-clock time) for a file of about 1.2 million rows. (The sample data in question was the StackOverflow questions CSV data set from here.)

Summary

Sorting a large CSV file with a few million rows is not as straightforward as it appears. Excel cannot load CSV files of this size. So we are left with having to load the CSV into a database and sort it there. Sample code was presented to do this using the H2 database.

Читайте также:  Компьютер запущен некорректно windows 10 как исправить через командную строку

In the next part of this article, we examine how the SQLite database performs in this regard.

XML Import Wizard

Quick Wizard to convert XML to Excel, Access and CSV. Can merge multiple XML files. Try it today.

Источник

Команда sort в Linux с примерами

Команда SORT в Linux используется для упорядочивания записей в определенном порядке в соответствии с используемой опцией. Это помогает в сортировке данных в файле построчно. Команда SORT имеет разные функции, которым она следует в результате команд. Во-первых, строки с номерами будут предшествовать буквенным строкам. Строки с строчными буквами будут отображаться раньше, чем строки с тем же символом в верхнем регистре.

Предпосылка

Вам необходимо установить Ubuntu на виртуальный ящик и настроить его. Пользователи должны быть созданы, чтобы иметь права доступа к приложениям.

Синтаксис

Пример

Это простой пример сортировки файла, имеющего данные об именах. Эти имена расположены не по порядку, и для того, чтобы упорядочить их, вам необходимо их отсортировать.

Итак, рассмотрим файл с именем file1.txt. Мы отобразим содержимое файла с помощью добавленной команды:

Теперь используйте команду для сортировки текста в файле:

Сохранить результат в другом файле

Используя команду сортировки, вы узнаете, что ее результат только отображается, но не сохраняется. Чтобы зафиксировать результат, нам нужно его сохранить. Для этого используется опция —o в команде сортировки.

Рассмотрим пример имени sample1.txt с названиями автомобилей. Мы хотим отсортировать их и сохранить полученные данные в отдельном файле. Во время выполнения создается файл с именем result.txt, и в нем сохраняется соответствующий вывод. Данные из sample1.txt передаются в результирующий файл, а затем с помощью —o соответствующие данные сортируются. Мы отобразили данные с помощью команды cat:

$ sort –o result.txt sample1.txt

Вывод показывает, что данные отсортированы и сохранены в другом файле.

Сортировка по номеру столбца

Сортировка выполняется не только по одному столбцу. Мы можем отсортировать один столбец из-за второго столбца. Приведем пример текстового файла, в котором есть имена и оценки студентов. Мы хотим расположить их в порядке возрастания. Поэтому мы будем использовать в команде ключевое слово —k. В то время как —n используется для числовой сортировки.

Поскольку есть два столбца, поэтому 2 используется с n.

Проверьте отсортированное состояние файла

Если вы не уверены, отсортирован данный файл или нет, удалите это сомнение с помощью команды, которая проясняет путаницу и отображает сообщение. Мы рассмотрим два основных примера:

Теперь рассмотрим несортированный файл с названиями овощей.

В команде будет использоваться ключевое слово —c. Это проверит, отсортированы ли данные в файле или нет. Если данные не отсортированы, то вывод будет отображать номер строки первого слова, в котором присутствует несортированность, а также слово.

Из приведенного вывода вы можете понять, что 3- е слово в файле было неуместным.

Отсортированные данные

В этом случае, когда данные уже организованы, больше ничего делать не нужно. Рассмотрим файл result.txt.

Из результата вы можете видеть, что не отображается сообщение, указывающее на то, что данные в соответствующем файле уже отсортированы.

Удалить повторяющиеся элементы

Вот самый полезный вариант. Это помогает удалить повторяющиеся слова в файле и упорядочить элемент файла. Он также поддерживает согласованность данных в файле.

Представьте, что имя файла file2.txt содержит имена субъектов, но одна тема повторяется несколько раз. Затем команда сортировки будет использовать ключевое слово —u для удаления дублирования и родства:

Теперь вы можете видеть, что повторяющиеся элементы удаляются из вывода и что данные также сортируются.

Сортировка с помощью конвейера в команде

Если мы хотим отсортировать данные файла, предоставив список каталога относительно размеров файлов, мы включим все соответствующие данные каталога. ’Ls’ используется в команде, и -l отобразит его. Pipe поможет в упорядоченном отображении файлов.

Читайте также:  Windows 10 нет русского языка интерфейса

Случайная сортировка

Иногда, выполняя какую-либо функцию, можно нарушить аранжировку. Если вы хотите расположить данные в любой последовательности и если нет критериев для сортировки, предпочтительнее случайная сортировка. Рассмотрим файл с именем sample3.txt, содержащий названия континентов.

Соответствующие выходные данные показывают, что файл отсортирован, а элементы расположены в другом порядке.

Сортировка данных из нескольких файлов

Одна из самых полезных команд сортировки — это одновременная сортировка данных из разных файлов. Это можно сделать с помощью команды find. Выходные данные команды find будут действовать как входные данные для команды после канала, который является командой сортировки. Ключевое слово Find используется для выдачи только одного файла в каждой строке, или мы можем сказать, что оно использует разрыв после каждого слова.

Например, давайте рассмотрим три файла с именами sample1.txt, sample2.txt и sample3.txt. Здесь «?» представляет собой любое число, за которым следует слово «образец». Find извлечет все три файла, и их данные будут отсортированы с помощью команды sort с инициативой pipe:

Выходные данные показывают, что данные всех файлов серии sample.txt отображаются и упорядочены в алфавитном порядке.

Сортировать с присоединением

Теперь мы представляем пример, который сильно отличается от тех, которые обсуждались ранее в этом руководстве. В дополнение к сортировке мы использовали join. Этот процесс выполняется таким образом, что оба файла сначала сортируются, а затем объединяются с помощью ключевого слова join.

Рассмотрим два файла, которые вы хотите объединить.

Теперь используйте приведенный ниже запрос, чтобы применить данную концепцию:

Из вывода видно, что данные обоих файлов объединены в отсортированном виде.

Сравнить файлы с помощью сортировки

Мы также можем принять концепцию сравнения двух файлов. Техника такая же, как и для стыковки. Сначала сортируются два файла, а затем данные в них сравниваются.

Рассмотрим те же два файла, что и в предыдущем примере. Sample2.txt и sample3.txt:

Данные сортируются и упорядочиваются поочередно. Начальная строка файла sample2.txt записывается рядом с первой строкой файла sample3.txt.

Заключение

В этой статье мы рассказали об основных функциях и параметрах команды сортировки. Команда сортировки Linux очень полезна для обслуживания данных и фильтрации всех бесполезных элементов из файлов.

Источник

JimHaughwout / sort_csv.py

#! /usr/bin/env python
«»»
Sort CSV file by multiple columns, writing output to sorted CSV file.
Recommended for files saved in Windows CSV format.
Useful for situations where data file is too large for Excel.
: param source_file.csv : source csv file. Must end in .csv
: param sort column 1 : first sort in Excel-like column number (i.e., 1 . N)
Use negative number to indicate descending sort,
Positive number to indicate ascending sort_step
: param sort column N : next sort in Excel-like column number (i.e., 1 . N)
Result is a sorted destination csv of name format input_file_sorted.csv.
EXAMPLES:
foo.csv has Column 1 = last_name, Column 2 = first_name
Column 3 = dob, Column 4 = height
Sort foo.csv by last_name then first_name then DOB:
sortCSV.py foo.csv 1 2 3
Sort the same but sort DOB descending (vs ascending):
sortCSV.py foo.csv 1 2 -3
Sort foo.csv by last_name then first_name then height, tallest to short:
sortCSV.py foo.csv 1 2 -4
Output written to foo_sorted.csv
Move to /usr/local/bin and chmod +x to use as command.
Can easily convert to function for real-time application.
«»»
import sys
import csv
from sys import argv
from operator import itemgetter
num_arguments = len ( argv )
# Check usage and provide help
if num_arguments == 2 and argv [ 1 ] in ( ‘-h’ , ‘-help’ ):
print «Usage: %s input_file.csv 1st_sort_col . nth_sort_col» % argv [ 0 ]
print «Example: %s foo.csv 1 2 -9» % argv [ 0 ]
print » \t Sorts foo.csv on 1st and 2nd columns (ascending) then 9th descending.»
sys . exit ()
elif num_arguments 3 : # Guidance on arguments to pass
usage = «Usage: %s input_file.csv 1st_sort_col . nth_sort_col» % argv [ 0 ]
error = «You passed only %d arguments» % num_arguments
sys . exit ( «%s — %s» % ( usage , error ))
if ‘.csv’ not in argv [ 1 ]: # Ensure using a CSV file
usage = «Usage: %s input_file.csv 1st_sort_col . nth_sort_col» % argv [ 0 ]
error = «You passed %r for input_file.csv» % argv [ 1 ]
sys . exit ( «%s — %s» % ( usage , error ))
# Create the output file as input with _sorted before .csv extension
input_file = argv [ 1 ]
output_file = input_file . replace ( ‘.csv’ , ‘_sorted.csv’ )
# Ensure you can open the source and target files
try :
source = open ( input_file , ‘r’ )
except :
e = sys . exc_info ()[ 0 ]
sys . exit ( «Error — Could not open input file %r: %s» % ( input_file , e ))
try :
target = open ( output_file , ‘w’ )
except :
e = sys . exc_info ()[ 0 ]
sys . exit ( «Error — Could not open output file %r: %s» % ( output_file , e ))
print » \n Sorting data from %r into %r, inside out» % ( input_file , output_file )
# Now create a list of sorting tuples where the first item is the index of
# the data object you wish to sort and the second item is the type of sort,
# Ascending (Reverse is False) or Descending (Reverse is True)
sorts = []
for i in range ( 2 , num_arguments ): # Skip script name and input filename
# Ensure you are passed Excel-like column numbers
try :
sort_arg = int ( argv [ i ])
except :
e = sys . exc_info ()[ 0 ]
sys . exit ( «Error — Sort column %r not an integer: %s.» % ( argv [ i ], e ))
if sort_arg == 0 :
sys . exit ( «Error — Use Excel-like column numbers from 1 to N» )
# Create a tuple for each as described above
if sort_arg > 0 :
sorts . append (( sort_arg — 1 , False )) # Convert column num to index num
else :
sorts . append ((( — 1 * sort_arg ) — 1 , True ))
# Read in the data creating a label list and list of one tuple per row
reader = csv . reader ( source )
row_count = 0
data = []
for row in reader :
row_count += 1
# Place the first row into the header
if row_count == 1 :
header = row
continue
# Append all non-header rows into a list of data as a tuple of cells
data . append ( tuple ( row ))
# Sort is stable as of Python 2.2. As such, we can break down the
# complex sort into a series of simpler sorts. We just need to remember
# to REVERSE the order of the sorts.
for sort_step in reversed ( sorts ):
print ‘Sorting Column %d («%s») Descending=%s’ % \
( sort_step [ 0 ] + 1 , header [ sort_step [ 0 ]], sort_step [ 1 ]) # +1 for Excel col num
data = sorted ( data , key = itemgetter ( sort_step [ 0 ]), reverse = sort_step [ 1 ])
print ‘Done sorting %d data rows (excluding header row) from %r’ % \
(( row_count — 1 ), input_file )
# Now write all of this out to the new file
writer = csv . writer ( target )
writer . writerow ( header ) # Write the header in CSV format
for sorted_row in data : # Wrtie the sorted data, converting to CSV format
writer . writerow ( sorted_row )
print ‘Done writing %d rows (sorted data plus header) to %r \n ‘ % \
( row_count , output_file )
# Be good and close the files
source . closed
target . closed
Читайте также:  Windows store ошибка 0x80070422

This comment has been minimized.

Copy link Quote reply

dineshkrp commented Jun 11, 2017

your code is very much user friendly & easy to understand, but i am facing one problem,

when i was trying to sort a 800 MB CSV file by a numeric field (-5), it is limited to maximum value «999» for that field. (but value range for that field is 1 to 20,000)

Please suggest how to overcome.

This comment has been minimized.

Copy link Quote reply

pwatts001 commented Mar 22, 2018

Did you resolve your issue?

I want to multi column sort a large CSV file with the final sort column containing a 9 digit long integer. Based on your comment it sounds like what I want to achieve is not possible?

You can’t perform that action at this time.

You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session.

Источник

Оцените статью