/ website / blog

extract columns with fields

February 29, 2020

About a month ago there was an article on Hacker News, “Why Learn Awk? (2016)". In the comments of that article was a thread started by jerf, which spoke directly to my own sentiments. Parsing columns of text should be simpler!

There are of course the timeless tools like awk and cut - which when combined with other arcane shell-isms can accomplish literally anything. But I wanted something that was simple, for a recuring use case that did not feel well served by the status quo.

To that end I have dusted off an old side project, fixed a few bugs, published a snap, and now, am pleased to announce!

The fields command can be built from source (GH), or installed as a snap. If you find bugs are have feature requests, by all means file an issue. I hope for this tool to become useful for many folks, not just me.

fields is a tool for parsing and selecting columns of text. One or more individual columns and/or ranges of columns can be selected by relative index. Indices can be positive (counting from the left) or negative (counting from the right). Ranges of indexes can be bounded (fixed number) or unbounded (e.g. select all input to the left or right of the n-th index).

Usage)

fields [options] <columns>

Syntax)

Options)

- newline: print a trailing newline character (default true)

Examples)

select a single column (from left)

$ fields 3 <<< "a b c d e f g"
    => c

select a single column (from right)

$ fields -- -3 <<< "a b c d e f g"
    => e

select columns to the right of N (from left)

$ fields 4: <<< "a b c d e f g"
    => d e f h

select columns to the right of N (from right)

$ fields -- -2: <<< "a b c d e f g"
    => f g

select range of columns

$ fields 2:5 <<< "a b c d e f g"
    => b c d e

select range of columns (reverse)

$ fields 5:2 <<< "a b c d e f g"
    => e d c b

select multiple combinations (comma separated)

$ fields -- -2,3:5,6: <<< "a b c d e f g"
    => f c d e f g

Happy hacking!

➡️ related posts in the go tools series ...