logan
logan

Reputation: 8346

awk -F command not working in linux

A simple awk command is not working..

Please suggest to me what's wrong here...

echo "hi hai hello" | awk -F"h" '{print $1}'

I tried in Linux and solaris, nothing showing...

Outputs :

-bash-3.00$ echo "hi hai hello" |awk -F"h" '{print $1}'

-bash-3.00$

Upvotes: 0

Views: 605

Answers (1)

Mark Reed
Mark Reed

Reputation: 95252

If the field delimiter is "h", then the fields are "", "i ", "ai ", and "ello". So the first field ($1) is the empty string, which awk is printing out as requested.

In general, if a string starts with the field delimiter, then the first field is empty. Similarly, if it ends with the field delimiter, awk considers there to be another empty field past that. And if there's a sequence of field delimiters, then they are considered to have empty fields between them.

One way to look at what's going on is to just loop over all the fields and print them out (maybe with quotation marks around them so you always get some visible output):

echo "hi hai hello" | awk -Fh '{for (i=1;i<=NF;++i) print " $"i" = \""$i"\"" }'
 $1 = ""
 $2 = "i "
 $3 = "ai "
 $4 = "ello"

As Ed Morton noted below, the exception to the above delimiter rules is whitespace, which is the default field separator if you don't specify one (or if you specify it as a space). In that case, any number of adjacent horizontal whitespace characters is considered a single field delimiter, and any leading or trailing whitespace is stripped:

echo " hi  hai  hello  " | awk '{for (i=1;i<=NF;++i) print " $"i" = \""$i"\"" }'
 $1 = "hi"
 $2 = "hai"
 $3 = "hello

Upvotes: 6

Related Questions