Shell Trivial awk question

Hello Experts,

I would like to print the 6th field of a string, so:

# echo "1 2 3 4 5 6 7 8" | awk '{print $6}'
6


But my delimiter is "/", not white space, so:

# echo "/1/2/3/4/5/6/7/8" | awk -F "/" '{print $6}'
5


So, now, fields are numbered from 0, not 1? I need then:

[root@snail ~]# echo "/1/2/3/4/5/6/7/8" | awk -F "/" '{print $7}'
6


However, if I try (first character is white space):

# echo " 1 2 3 4 5 6 7 8" | awk '{print $6}'
6


I'm confused: How does awk number fields/columns?

Apologies for such a trivial question.
 
Why don't you simply use cut(1)?

echo "/1/2/3/4/5/6/7/8" | cut -d'/' -f 7

As for the awk(1) issue, the leading spaces are silently ignored. The leading slashes however are not. That's why the position changes.
 
In other words there is an empty string before the first instance of the delimiter / in "/1/2/3/4/5/6/7/8" meaning the "1" is in position 2 and the empty string is at position 1.
 
SirDice,

Thank you for the quick reply and suggestion.

I should then note that while the behavior of awk(1) does depend on the kind of delimiter if the delimiter is the first character of the string:

# echo "/1/2/3/4/5/6/7/8" | awk -F "/" '{print $6}'
5


# echo " 1 2 3 4 5 6 7 8" | awk '{print $6}'
6


while the behavior of cut(1) does not:

# echo "/1/2/3/4/5/6/7/8" | cut -d '/' -f 6
5


# echo " 1 2 3 4 5 6 7 8" | cut -d ' ' -f 6
5


Thanks again for your quick help.
 
' ' is special-cased in the awk code. It is considered whitespace, not a single space character, near line 289:
Code:
  } else if ((sep = *inputFS) == ' ') {  /* default whitespace */
  for (i = 0; ; ) {
  while (*r == ' ' || *r == '\t' || *r == '\n')
  r++;
  if (*r == 0)

therefore:

echo "/1/2" | awk -F "/" '{print $2}'

and

echo " 1 2" | awk -F "\\\ " '{print $2}'

will return what you expect.
It's subtle, as ever, quoting from awk(1)
An input line is normally made up of fields separated by white space,
or by regular expression FS.
 
And thank you too amnixed, while I've used awk for years, it never occurred to me that the delimiter worked in this manner (where's the smiley smacking itself in the forehead when you need it).
 
Back
Top