How Do You Get awk to Use a Colon or a Semicolon as a Field Separator?

Problem scenario
You run a command such as this, with the goal of printing the number of occurrences of "foo":

grep -icR foo * | awk '{fs=":"; print $2}'

It does not do what you want it to do.  You want the field separator to be a colon.  It is not working.  How do you print the element after a ":" (colon) with an awk utility?

Technically awk is a programming language; but it is also a utility.  Use this command instead:

grep -icr foo *  | awk --field-separator=":" '{print $2}'

The syntax above uses awk in a different way to recognize the ":" (colon) as a field separator.  With the "--field-separator" syntax above, replacing the colon with a semicolon will allow you use to use a semicolon as a field separator too.

Leave a comment

Your email address will not be published. Required fields are marked *