3 awk snippets

Strip characters from a field in 'awk'

E.g., the following command strips alpha characters from the second (tab delimited) field.

awk -F"\t" '{gsub(/[A-Za-z]/,"",$2); print $2 }'
Tagged linux, awk, tool and one-liner.

 

Some 'awk' basics

Extract tab delimited fields from a file:

$ awk -F"\t" '{print "field one=" $1 "; field two=" $2 }' file
Tagged linux, awk, tool and cheatsheet.

 

Create a simple histogram or bar-chart in bash

The following script accepts (via stdin) input like this:

foo 10
bar 21
xyzzy 12

and generates (to stdout) a bar-chart like this:

+-------+----+
|   foo | 10 | ##########
|   bar | 21 | #####################
| xyzzy | 12 | ############
+-------+----+

where the width of the headings (category and count) is automatically determined by the input values and the width of the bar chart (the number of # characters) is automatically scaled to fit within the current terminal width.

It also demonstrates a few intermediate level awk features such as passing variables (via the -v parameter) and variable-width printf statements (via %*s).

Published 28 Feb 2018
Tagged linux, bash, data, text and awk.

 

This page was generated at 4:16 PM on 26 Feb 2018.
Copyright © 1999 - 2018 Rodney Waldhoff.