Conceptintro
Delimited text
Also called delimiter-separated values, DSV, delimited file, field separator, field delimiter, record separator, delimiter collision, flat file.
Delimited text stores a table as lines of text: each line is a record and a delimiter character separates its fields. A format must say what happens when a field holds the delimiter.
- Applies to
- core-languages
Idea
Delimited text stores a table as plain text. Delimiter-separated values (DSV) are "a way of storing tabular data by separating the fields (values) of each row with a specific character as a delimiter"1. Each line is a record, and one character separates its fields. "Any character may be used to separate field values, and the more commonly used include comma , tab , colon , vertical bar (a.k.a. pipe) and space"1. A split at the delimiter reads such a line, until a field holds the delimiter.
import csv
import io
# Each line is a record, and a delimiter separates its fields.
line = "alice:x:1000:1000:Alice:/home/alice:/bin/sh"
fields = line.split(":")
print(len(fields), fields[0], fields[-1])
# Delimiter collision: a field holds the delimiter.
row = ["25 May", "Bloggs, Fred", "C"]
naive = ",".join(row)
print(naive, "->", len(naive.split(",")), "fields")
# CSV puts quotes around such a field, and a CSV reader finds three fields.
buf = io.StringIO()
csv.writer(buf, lineterminator="\n").writerow(row)
text = buf.getvalue()
print(text, end="")
print(next(csv.reader(io.StringIO(text))))
7 alice /bin/sh
25 May,Bloggs, Fred,C -> 4 fields
25 May,"Bloggs, Fred",C
['25 May', 'Bloggs, Fred', 'C']
The first line has the shape of a line of /etc/passwd, where "Each line of the file describes a single user, and contains seven colon-separated fields"2. A split at the colon gives the seven fields. The second record has a comma in a field, so a split at the comma gives four fields, not three. This is delimiter collision: "what happens when the delimiter character is embedded in a field value without accommodation for doing so"1. The csv module3 puts quotes around the field, and its reader finds the three fields again.
How it works
Records and fields. "In general a format is categorized as DSV if it is lines of delimiter-separated values (where lines are newline -separated)"1. "The first row is sometimes a special record containing the column names"1. DSV is a family of formats: "DSV is a categorization of data format , not a particular format"1. So each file needs a convention: the delimiter, the line ending, the header row, and what to do when a field holds the delimiter or a newline.
Three ways to handle collision. "Some DSV conventions simply disallow a delimiter in a value while others provide a mechanism that allows for embedding delimiters"1. The next block shows the three common ways on the same record.
import csv
import io
row = ["C:\\temp", 'say "hi"', "a:b", ""]
# 1. Forbid: TSV has no way to write a tab in a field, so check and refuse.
def tsv_line(fields):
for f in fields:
if "\t" in f or "\n" in f:
raise ValueError(f"field {f!r} holds a tab or a newline")
return "\t".join(fields)
try:
tsv_line(["ok", "a\tb"])
except ValueError as e:
print("forbid:", e)
# 2. Quote: CSV puts quotes around a field and doubles each quote in it.
buf = io.StringIO()
csv.writer(buf, delimiter=":", lineterminator="\n").writerow(row)
print("quote: ", buf.getvalue(), end="")
print(" back:", next(csv.reader(io.StringIO(buf.getvalue()), delimiter=":")) == row)
# 3. Escape: a backslash makes the next character ordinary, as in Unix files.
def escape(f, sep=":"):
return f.replace("\\", "\\\\").replace(sep, "\\" + sep).replace("\n", "\\n")
def split_escaped(line, sep=":"):
fields, cur, i = [], [], 0
while i < len(line):
c = line[i]
if c == "\\" and i + 1 < len(line):
nxt = line[i + 1]
cur.append("\n" if nxt == "n" else nxt)
i += 2
continue
if c == sep:
fields.append("".join(cur))
cur = []
else:
cur.append(c)
i += 1
fields.append("".join(cur))
return fields
line = ":".join(escape(f) for f in row)
print("escape:", line)
print(" back:", split_escaped(line) == row)
forbid: field 'a\tb' holds a tab or a newline
quote: "C:\temp":"say ""hi""":"a:b":
back: True
escape: C\:\\temp:say "hi":a\:b:
back: True
- Forbid. TSV does not let a field hold the delimiter: "Note that fields that contain tabs are not allowable in this encoding"4. The reader is a plain split, but the writer must check each field and refuse a field with a tab or a newline.
- Quote. CSV puts quotes around a field. "Fields containing line breaks (CRLF), double quotes, and commas should be enclosed in double-quotes"5, and "If double-quotes are used to enclose fields, then a double-quote appearing inside a field must be escaped by preceding it with another double quote"5. The reader must track whether it is inside quotes, so a plain split does not work.
- Escape. Unix files put a backslash before the delimiter. "Data files in this style are expected to support inclusion of colons in the data fields by backslash escaping"6. "The Unix way would be to simply escape the separator with a backslash, and have a double escape represent a literal backslash"6. This gives "a single special case (the escape character) to check for when parsing the file"6.
The quote form and the escape form both give the record back, as the two back: True lines show. The escape form also needs a rule for the newline, so the code writes it as \n.
Split rules. A split at one character and a split at white space give different fields. In Python, "If sep is given, consecutive delimiters are not grouped together and are deemed to delimit empty strings"7. With no separator, "runs of consecutive whitespace are regarded as a single separator, and the result will contain no empty strings at the start or end if the string has leading or trailing whitespace"7.
# A split at one character keeps empty fields.
print("a::b:".split(":"))
print("".split(":"))
# A split at white space merges runs and drops the ends.
print(" a b ".split())
print(" a b ".split(" "))
# The ASCII unit separator (0x1F) and record separator (0x1E) rarely occur in text.
US, RS = "\x1f", "\x1e"
data = RS.join(US.join(r) for r in [["a, b", "c\td"], ["e", ""]])
print(repr(data))
print([r.split(US) for r in data.split(RS)])
['a', '', 'b', '']
['']
['a', 'b']
['', '', 'a', '', 'b', '']
'a, b\x1fc\td\x1ee\x1f'
[['a, b', 'c\td'], ['e', '']]
The record a::b: has four fields, and two of them are empty. A split at white space suits text that people align with spaces, but it cannot show an empty field. awk has the same two rules. "If FS is , skip leading and trailing and characters; fields shall be delimited by sets of one or more or characters"8. "Otherwise, if FS is any other character c , fields shall be delimited by each single occurrence of c"8. The shell splits words at the characters of IFS, and "The shell shall set IFS to when it is invoked"9.
The last lines of the block use two control characters as delimiters. "ASCII and Unicode include control characters that are intended to be used as delimiters: File Separator , Group Separator , Record Separator , and Unit Separator"1. A comma, a tab or a newline in a field then needs no quotes. But "Use of these in DSV data is relatively uncommon"1, and people cannot see or type them easily.
The Unix convention. Many Unix files and tools use delimited text. "/etc/passwd format (one record per line, colon-separated fields) is very traditional under Unix and frequently used for tabular data"6. "This format is most appropriate when the data is tabular, keyed by a name (in the first field), and records are typically short (less than 80 characters long). It works well with traditional Unix tools"6. The cut utility takes fields: "-d delim Set the field delimiter to the character delim . The default is the "10. "Old-school Unix practice used to favor tabs, a preference reflected in the defaults for cut(1) and paste(1)"6. awk writes its output fields with OFS, "The print statement output field separator; by default"8. These tools have no quotes, so they work when no field holds the delimiter.
In languages
| Language | Verdict | Note |
|---|---|---|
| Python | Standard library | Str.split with a separator keeps empty fields, str.split with no argument splits at runs of white space, and the csv module reads and writes fields with quotes. The three run blocks of this page show them, so no example file exists. |
| C++ | Standard library | |
| Java | Standard library | |
| C | Standard library | |
| C# | Standard library | String.Split takes one or more separator characters, and StringSplitOptions.RemoveEmptyEntries drops the empty fields. No example file exists. |
| JavaScript | Standard library | |
| TypeScript | Standard library | TypeScript has the String.prototype.split of JavaScript, so the JavaScript example applies. No example file exists. |
| Go | Standard library | |
| Rust | Standard library | |
| Kotlin | Standard library | Kotlin has its own split for strings, and the JVM has String.split as in the Java example. No example file exists because kotlinc is not installed. |
| SQL | Standard library | SQL engines load and unload delimited files with bulk commands, such as COPY in PostgreSQL, and PostgreSQL has split_part to take one field from a string. The commands differ from engine to engine. |
| Bash | Native | |
| PowerShell | Native | The -split operator splits a string at a pattern, and Import-Csv reads a file with a -Delimiter parameter. No example file exists because pwsh is not installed. |
| HTML | Does not apply | Markup has no fields or records to split. A table element can show the rows of a delimited file. |
| CSS | Does not apply | Style sheets have no fields or records to split. |
| Regular expressions | Native | A split at a pattern such as a comma with optional spaces handles some variations, and a pattern such as [^:]* matches one field. A pattern alone does not handle quoted fields well. |
| Language | Verdict | Mechanism |
|---|---|---|
| Python | stdlib | str.split(sep) keeps empty fields; str.split() splits at white space; the csv module handles quotes |
| JavaScript | stdlib | String.prototype.split keeps empty fields; its limit drops the rest of the line |
| TypeScript | stdlib | the split of JavaScript |
| Java | stdlib | String.split takes a regular expression and drops trailing empty strings unless the limit is negative |
| Kotlin | stdlib | its own split for strings, and the String.split of the JVM |
| C# | stdlib | String.Split with StringSplitOptions |
| Go | stdlib | strings.Split, strings.SplitN, strings.Fields; encoding/csv for quotes |
| Rust | stdlib | str::split, splitn, split_whitespace |
| C | stdlib | strtok merges delimiters; strsep (BSD) keeps empty fields |
| C++ | stdlib | std::getline with a delimiter character |
| Bash | native | IFS and read; the tools cut -d and awk -F |
| PowerShell | native | the -split operator; Import-Csv -Delimiter |
| SQL | stdlib | bulk loaders such as COPY in PostgreSQL; split_part in PostgreSQL |
| Regex | native | a split at a pattern; a pattern such as [^:]* for one field |
| HTML | n/a | markup has no fields to split |
| CSS | n/a | style rules have no fields to split |
Each language has a split, but the splits differ at the edges. Java's split drops empty fields at the end: "Trailing empty strings are therefore not included in the resulting array"11. With a negative limit, "the pattern will be applied as many times as possible and the array can have any length"11. Go's Fields splits at white space, and "Every element of the returned slice is non-empty"12. In Rust, "Contiguous separators are separated by the empty string"13. The limit of JavaScript "splits the string at each occurrence of the specified separator , but stops when limit entries have been placed in the array"14, so the rest of the line is lost.
C has two calls. strtok "searches the search target for the first character that is not contained in the separator string"15, so it skips a run of delimiters, and "This function is destructive: it writes the '\0' characters in the elements of the string str"15. "The strsep () function was introduced as a replacement for strtok(3) , since the latter cannot handle empty fields"16. In C++, std::getline with a delimiter reads one field at a time, but after the last delimiter, "If no characters were extracted for whatever reason (not even the discarded delimiter), getline sets failbit and returns"17, so the loop loses an empty last field.
The example files show the same record a::b: in each language.
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
int main() {
// getline with ':' reads one field at a time.
std::istringstream in("a::b:");
std::vector<std::string> fields;
std::string f;
while (std::getline(in, f, ':')) {
fields.push_back(f);
}
// The empty field after the last ':' is lost: getline fails at the end.
std::cout << fields.size() << " fields:";
for (const auto& s : fields) std::cout << " \"" << s << "\"";
std::cout << "\n";
}
3 fields: "a" "" "b"
- Verdict: stdlib.
std::getlinewith a delimiter reads one field at a time and keeps empty fields between delimiters. After the last:it extracts no characters and fails, so the loop loses the empty last field. Count the delimiters, or test whether the line ends with one, to keep it.
import java.util.Arrays;
import java.util.regex.Pattern;
public class Main {
public static void main(String[] args) {
// split takes a regular expression and drops trailing empty strings.
System.out.println(Arrays.toString("a::b:".split(":")));
// A negative limit keeps them.
System.out.println(Arrays.toString("a::b:".split(":", -1)));
// "|" is a regular expression that matches the empty string.
System.out.println(Arrays.toString("a|b".split("|")));
// Pattern.quote makes it a plain character.
System.out.println(Arrays.toString("a|b".split(Pattern.quote("|"))));
// A limit of 2 keeps the rest of the line in the last field.
System.out.println(Arrays.toString("k=v=w".split("=", 2)));
}
}
[a, , b]
[a, , b, ]
[a, |, b]
[a, b]
[k, v=w]
- Verdict: stdlib.
String.splittakes a regular expression, and with no limit it drops the empty strings at the end, so a record with empty last fields comes back shorter. A negative limit keeps them. A separator such as|or.must be quoted withPattern.quote.
#define _DEFAULT_SOURCE /* strsep */
#include <stdio.h>
#include <string.h>
int main(void) {
char a[] = "a::b:";
char b[] = "a::b:";
/* strtok skips runs of delimiters, so it loses the empty fields. */
int n = 0;
for (char *t = strtok(a, ":"); t != NULL; t = strtok(NULL, ":")) {
printf("strtok %d: \"%s\"\n", ++n, t);
}
/* strsep returns each field, also the empty ones. */
n = 0;
char *rest = b;
char *t;
while ((t = strsep(&rest, ":")) != NULL) {
printf("strsep %d: \"%s\"\n", ++n, t);
}
return 0;
}
strtok 1: "a"
strtok 2: "b"
strsep 1: "a"
strsep 2: ""
strsep 3: "b"
strsep 4: ""
- Verdict: stdlib.
strtoktreats a run of delimiters as one, so it loses the empty fields, and it writes into the string.strsepis not in ISO C, but glibc and the BSDs have it, and it returns each field, also the empty ones.
// split with a string keeps every empty field, also the last one.
console.log(JSON.stringify("a::b:".split(":")));
console.log(JSON.stringify("".split(":")));
// For fields split by white space, trim first and split at runs of it.
console.log(JSON.stringify(" a b ".trim().split(/\s+/)));
// A limit stops after that many fields and drops the rest of the line.
console.log(JSON.stringify("k=v=w".split("=", 2)));
["a","","b",""]
[""]
["a","b"]
["k","v"]
- Verdict: stdlib.
String.prototype.splitwith a string separator keeps each empty field, also the last one. Itslimitargument stops after that many fields and drops the rest of the line, so a field that holds the separator needsindexOfandsliceinstead.
package main
import (
"fmt"
"strings"
)
func main() {
// Split keeps every empty field, also the last one.
fmt.Printf("%q\n", strings.Split("a::b:", ":"))
fmt.Printf("%q\n", strings.Split("", ":"))
// Fields splits at runs of white space and drops the ends.
fmt.Printf("%q\n", strings.Fields(" a b "))
// SplitN with n=2 keeps the rest of the line in the last field.
fmt.Printf("%q\n", strings.SplitN("k=v=w", "=", 2))
}
["a" "" "b" ""]
[""]
["a" "b"]
["k" "v=w"]
- Verdict: stdlib.
strings.Splitkeeps each empty field.strings.Fieldssplits at runs of white space and returns only fields that are not empty.strings.SplitNwith 2 keeps the rest of the line, with its separators, in the last field. Theencoding/csvpackage reads fields with quotes.
fn main() {
// split keeps every empty field, also the last one.
let v: Vec<&str> = "a::b:".split(':').collect();
println!("{:?}", v);
let v: Vec<&str> = "".split(':').collect();
println!("{:?}", v);
// split_whitespace splits at runs of white space and drops the ends.
let v: Vec<&str> = " a b ".split_whitespace().collect();
println!("{:?}", v);
// splitn(2, ..) keeps the rest of the line in the last field.
let v: Vec<&str> = "k=v=w".splitn(2, '=').collect();
println!("{:?}", v);
}
["a", "", "b", ""]
[""]
["a", "b"]
["k", "v=w"]
- Verdict: stdlib.
str::splitkeeps each empty field, andsplit_whitespacesplits at runs of white space.splitn(2, ..)keeps the rest of the line in the last field. The standard library has no CSV reader.
line='a::b:'
# read splits at each ':' in IFS, but drops the empty field at the end.
IFS=: read -r -a f <<< "$line"
echo "read: ${#f[@]} fields"
# cut and awk count the empty field at the end.
echo "cut field 4: [$(printf '%s\n' "$line" | cut -d: -f4)]"
printf '%s\n' "$line" | awk -F: '{ print "awk: " NF " fields" }'
# The default IFS splits at runs of white space and drops the ends.
read -r -a w <<< ' a b '
echo "white space: ${#w[@]} fields"
read: 3 fields
cut field 4: []
awk: 4 fields
white space: 2 fields
- Verdict: native.
readwithIFS=:splits at each colon, but Bash drops the empty field at the end of the line, as the output shows.cut -d:andawk -F:count it. With the defaultIFS, a run of spaces is one separator. The tools have no quotes, so a field cannot hold the delimiter.
Variations and related ideas
- CSV and TSV. The two common members of the family have their own pages, CSV with quotes and TSV with no collision at all.
- Fixed width. The other common way to store a table as text puts each column at fixed character positions, which limits the length of each value. Wikipedia names it as the alternative, and says that DSV "supports field values of any length"1.
- Other record separators. A format can use something other than a newline to end a record. The cookie-jar format of
fortune"simply uses newline followed by %% (or sometimes newline followed by % ) as a record separator"6, andawkreads paragraphs as records whenRSis empty8. - Split a string. The split call itself is in Split a string, and the line endings that end each record are in Line ending.
Pitfalls
- A field holds the delimiter. A split then gives too many fields, as the first example shows. A rare delimiter does not fix it: "even though a character may seem unusual, in practice, it might be used and then result in a processing error"1. Check the number of fields of each record, and use quotes or escapes for data that you do not control.
- Empty fields vanish.
strtok, Java'ssplitwith no limit,std::getlineandreadin Bash lose some empty fields, as the example files show151117. A record with an empty last field then has one field fewer than the header. - Spaces and tabs look the same. The Art of Unix Programming describes "the many small irritations that ensue from the fact that tabs and spaces are not visually distinguishable"6. An editor that turns tabs into spaces breaks a file that uses tabs.
- The separator is a pattern. Java's
splitworks "around matches of the given regular expression"11, so a separator such as|or.does not split at that character. Quote the separator. - A CR at the end of the last field. A program that splits a file with CR LF endings at LF leaves a CR in the last field of each record. See Line ending.
- Quotes differ between programs. For CSV, "because the format rules are complex and underspecified, different implementations diverge in their handling of edge cases"6. Use a CSV library for CSV, and test a file from another program before you trust it.
Cost
A split looks at each character once, so it is linear in the length of the line. It makes one new string for each field, and a program that needs only one field can stop at that field. A reader that handles quotes keeps one state, inside or outside quotes, and is still one pass. A program can read a file one record at a time, so the memory depends on the longest record, not on the size of the file. In CSV a quoted field can hold newlines, so one record can span many lines.
References
- Delimiter-separated values, Wikipedia, Introduction, Format, Delimiter collision
- passwd(5), Linux manual page, Description
- The Python Standard Library, csv, csv.writer, csv.reader
- IANA, Media type registration of text/tab-separated-values, Definition of tab-separated-values
- RFC 4180: Common Format and MIME Type for Comma-Separated Values (CSV) Files, 2. Definition of the CSV Format
- Eric S. Raymond, The Art of Unix Programming, Chapter 5, Data File Metaformats, DSV Style, Cookie-Jar Format
- The Python Standard Library, Built-in Types, str.split
- The Open Group, POSIX.1-2024, awk, Variables and Special Variables (FS, OFS, RS)
- The Open Group, POSIX.1-2024, Shell Command Language, 2.5.3 Shell Variables, IFS
- The Open Group, POSIX.1-2024, cut, Description, Options (-d, -f)
- String, Java SE 25 API, split(String, int)
- Go standard library, package strings, Fields, Split, SplitN
- Rust standard library, primitive type str, split, split_whitespace
- String.prototype.split(), MDN Web Docs, Parameters, Description
- strtok, strtok_s, cppreference.com, Description, Notes
- strsep(3), Linux manual page, Description, History
- std::getline, cppreference.com, Description
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H0 no proof |
|
| Lean | L0 no Lean part |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag MTQA77 Edit this page History Report an error Markdown