Cheatsheet

I'm not googling that again

Grab every other line from a file using awk

I had this very specific need recently where I needed to parse a configuration file with properties that had both defaults and overrides from environment variables, something along the lines of:

some-property=some-value
some-property=${SOME-PROPERTY-OVERRIDE}
another-property=another-value
another-property=${ANOTHER-PROPERTY-OVERRIDE}

I wanted to get only the defaults which effectively means I needed to get every other line from the file and that's were awk comes to save the day:

# Grab every other line from the file.
# Line numbering starts at 1.
awk 'NR % 2' config.file

# > some-property=some-value
#   another-property=another-value

The NR variable is quite useful in awk. For example, it can be used to display ranges of a file or always keeping the header when displaying data organized in a table:

# Show the first line from the output
#  and filter for lines that contain 'memcached'
awk 'NR == 1 || /memcached/' <(docker images)

This probably can be done also by using a --filter flag in the images command but you get the point.