Skip to content

Instantly share code, notes, and snippets.

@mvitaly
Last active January 24, 2022 13:22
Show Gist options
  • Save mvitaly/106347c5edfa6614d5311b228b4446c9 to your computer and use it in GitHub Desktop.
Save mvitaly/106347c5edfa6614d5311b228b4446c9 to your computer and use it in GitHub Desktop.
DataGrip extractor for txt file with fixed length columns
SEPARATOR = "|"
SPACE = " "
CORNER = "+"
LINE = "-"
NEWLINE = System.getProperty("line.separator")
def outRecord(columnLengths, row, separator=SEPARATOR, padding=SPACE) {
OUT.append(separator)
[columnLengths, row].transpose().each { size, value ->
OUT.append(padding + value.padRight(size, padding) + padding + separator)
};
OUT.append(NEWLINE)
}
if (!TRANSPOSED) {
COLUMN_NAMES = COLUMNS.collect { col -> col.name() }
def formattedRows = ROWS.collect { row -> COLUMNS.collect { col -> FORMATTER.format(row, col) } }
def columnLengths = formattedRows.inject(COLUMN_NAMES.collect { col -> col.size() }, { columnLengths, row ->
[columnLengths, row.collect { it.length() }].transpose().collect { collectedSize, size -> Math.max(collectedSize, size) }
})
// OUTPUT
// HEADER
outRecord(columnLengths, COLUMNS.collect { '' }, CORNER, LINE)
outRecord(columnLengths, COLUMN_NAMES)
outRecord(columnLengths, COLUMNS.collect { '' }, CORNER, LINE)
formattedRows.each { row -> outRecord(columnLengths, row) }
outRecord(columnLengths, COLUMNS.collect { '' }, CORNER, LINE)
} else {
def formattedRows = COLUMNS.collect { col -> new ArrayList<String>([col.name()]) }
ROWS.each { row -> COLUMNS.eachWithIndex { col, i -> formattedRows[i].add(FORMATTER.format(row, col)) } }
def columnLengths = (0..formattedRows[0].size-1).collect { idx -> formattedRows.inject(0, { collectedSize, row -> Math.max(collectedSize, row[idx].length()) } ) }
// OUTPUT
outRecord(columnLengths, COLUMNS.collect { '' }, CORNER, LINE)
formattedRows.each { row -> outRecord(columnLengths, row) }
outRecord(columnLengths, COLUMNS.collect { '' }, CORNER, LINE)
}
@nzbart
Copy link

nzbart commented Sep 27, 2018

Exactly what I wanted, despite this limitation. Thanks for taking the time to post this!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment