AWK substr

1 minute read Published:

Substr is a neat little part of AWK.

I recently needed to get the first character of a column in a space separated file, and while there are a ton of ways to do this, I figured that Awk’s substr function would make the most sense.

substr(string, start, length): This will return length characters from string starting at position start. start is not zero-based, so 1 will be the first character, 2 will be the second, and so-on. On most systems, 0 still works for the first character, even though 1 will also return the first character.

Let’s start with an example file (example.txt):

1 foo bar
2 Example example2
3 bar foo
4 fizz buzz

To get the first letter of the second column, we can use:

awk '{print substr($2, 1, 1)}' < example.txt

and the output would be:

f
F
b
f