With awk, What Do You Do to Get a Colon To Be Recognized as a Separator of Fields?

Problem scenario
You have Awk 4.1.3 installed.  The default field separator in awk is a space.  You want to assign it to a different character -- specifically a colon ":".  You have a string with a colon assigned to the variable "y".  You have tried these things:

echo $y | awk -F ":" '/1/ {print $NF}'  # this prints nothing
echo $y | awk '{FS=":"; print $1}'  # this prints y
echo $y | awk 'BEGIN { FS=":" } /1/ { print $2}' # this prints nothing

The above commands do not recognize the ":" as the field separator.  You think regular letters would have worked as a string, but you find the colon ":" to behave differently.  What do you do to get a colon to be recognized as a separator of fields?

In some ways, this question for those Awk experts reading, is what is the functional difference between awk's "--field-separator" contrasted with Awk's "FS" reserved flag?

To find the version of awk use this command: awk -W version.  Be sure you have a new version (e.g., around 4.1.3).  To upgrade on a Debian/Ubuntu server, run this:  sudo apt-get -y upgrade gawk

For reasons we do not understand, use the unabbreviated "--field-separator" to assign the non-default character to.  The behavior is different.  We find the [more verbose] "--field-separator" works more reliably and predictably.  Here is an example:

echo $y | awk --field-separator=":" '{print $1}'

(We know the awk command is technically a programming language that was an antecedent to Perl.  Today awk is thought of chiefly as a Bash command or utility.)

Leave a comment

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