1

I have some lines like the following saved into a txt file:

 Mike Tyson    1    2    3    4    5
 Alì     1    2   3   4   5

every different fields are separated with a tab, but in the first field I could have 2 words separated only by a space. how can I have a correct interpretation by awk? I want only the values separated by tabs like this:

 $a=mike tyson
 $b=1
 $c=2
 etc etc....

now, i'm using a while cycle to read each line, finished by

 done < <(awk 'NR>0' file.txt)

but this command sees the value "mike tyson" as two different fields.

rschirin
  • 1,939
  • 10
  • 34
  • 44
  • possible duplicate of [Tab separated values in awk](http://stackoverflow.com/questions/5374239/tab-separated-values-in-awk) – McGarnagle Oct 17 '13 at 20:40
  • 4
    Using a while loop in shell to parse a file is almost always the wrong approach. tell us what you're doing with sample input and expected output and we can help you do it the right way. – Ed Morton Oct 17 '13 at 20:48

2 Answers2

3

Try to change to:

done < <(awk -F"\t" 'NR>0' file.txt)

awk does see any space (blanks and tabs) as filed separators. Setting it to only tab, prevents it divide files with space.

Jotne
  • 40,548
  • 12
  • 51
  • 55
  • 1
    -F'\t' is right direction, but i doubt this will work for a while loop. in fact, with/without the `-F'\t'`, the awk line would give same output, right? or I am wrong... – Kent Oct 17 '13 at 20:59
  • `-F` will make a difference if the processing logic is within `awk`. In the OP this is not the case: you could replace `<(awk -F"\t" 'NR>0' file.txt)` with just `file.txt` (no `awk`), it will make no difference for the `while` loop. – janos Oct 18 '13 at 04:36
1

The problem is not with awk, as you are interpreting the columns in bash.

Maybe you're looking for something like this:

IFS=$'\t'
while read a b; do
    echo a=$a
    echo b=$b
done < file.txt

In your sample code awk doesn't seem to play any role btw.

janos
  • 120,954
  • 29
  • 226
  • 236
  • that will fail in various cryptic ways given various input values. – Ed Morton Oct 17 '13 at 22:28
  • @EdMorton you mean, it *might* fail under some circumstances. If the poster has a corner case where this doesn't work, he can post it and we can offer something better, maybe. – janos Oct 18 '13 at 09:49
  • I doubt if the poster would have any reason to suspect the cases in which this would fail and he might be using it for a year before he hits one and then has to figure out what the heck just happened. It's simply not the right approach and on top of that doesn't do the minimal stuff that you should ALWAYS do with a shell script unless you have a very specific reason not to (i.e. use `-r` with `read`, quote your variables, and use `printf` instead of `echo`). – Ed Morton Oct 18 '13 at 12:22