print $0 removes the field delimiter

  • Follow


Hello all,
I hope someone can help me understand this strange behaviour of awk:

file input.txt:
A, B, C,
D, E, Y,
G, H, I,

Awk command I use:
cat input.txt | awk -F, '{if ($3 == "Y") {$1=$3}; {print $0}'

What I expect the output to be is:
A, B, C,
Y, E, Y,
G, H, I,

What the output actually is:
A, B, C,
Y E Y
G, H, I,
(note the field delimiter on the second line is switched back to the 
default one, that is <space>, the comma is lost)

The only way I can get the desired output is:
cat input.txt | awk -F, '{(if $1 == "D") {$1=X}; 
{printf("%s,%s,%s,\n"),$1,$2,$3}'

I know there are probably many other ways to accomplish the same result, 
but that's not the point: the point is: Why does print $0 remove the 
commas? It look like, once it finds a line to process (test is true), it 
processes it, then forgets that it was using a non-default delimiter and 
when it recreates $0 it uses the default delimiter...?? :(

Any clarification would be greatly appreciated.

TIA
/andrea


0
Reply anfi 1/16/2004 2:29:00 PM

anfi <anfi2000@hotmail.com> wrote:
> Hello all,
> I hope someone can help me understand this strange behaviour of awk:

> file input.txt:
> A, B, C,
> D, E, Y,
> G, H, I,

> Awk command I use:
> cat input.txt | awk -F, '{if ($3 == "Y") {$1=$3}; {print $0}'

> What I expect the output to be is:
> A, B, C,
> Y, E, Y,
> G, H, I,

> What the output actually is:
> A, B, C,
> Y E Y
> G, H, I,
> (note the field delimiter on the second line is switched back to the 
> default one, that is <space>, the comma is lost)

> The only way I can get the desired output is:
> cat input.txt | awk -F, '{(if $1 == "D") {$1=X}; 
> {printf("%s,%s,%s,\n"),$1,$2,$3}'

> I know there are probably many other ways to accomplish the same result, 
> but that's not the point: the point is: Why does print $0 remove the 
> commas? It look like, once it finds a line to process (test is true), it 
> processes it, then forgets that it was using a non-default delimiter and 
> when it recreates $0 it uses the default delimiter...?? :(

Because you didn't set OFS, try something in the lines of:

awk 'BEGIN{FS=OFS=","}{if ($3~"Y") $1=$3} {print}' input.txt


-- 
Michael Heiming

Remove +SIGNS and www. if you expect an answer, sorry for 
inconvenience, but I get tons of SPAM
1
Reply Michael 1/16/2004 2:45:45 PM


> Because you didn't set OFS, try something in the lines of:
> 
> awk 'BEGIN{FS=OFS=","}{if ($3~"Y") $1=$3} {print}' input.txt

Thanks for the quick answer! That did the trick ;)
/andrea

0
Reply anfi 1/16/2004 3:08:11 PM

2 Replies
857 Views

(page loaded in 0.064 seconds)

Similiar Articles:













7/23/2012 10:20:04 AM


Reply: