SOaddict SOaddict - 6 months ago 15
Linux Question

Assign line number to one of the fields based on the no. of fields in each row

I need to manipulate one of my data files using awk command like this. How can I accomplish this using awk? Any inputs would be appreciated. Thank you.

1) Get the no. of fields for each row.
(a) If the count_of_fields = 'x' then assign a value to nth field in each row.


Input :-

1,x,A,B
2,A,B,C
3,x,C,D
4,D,E,F,G
5,x,E,F


**

Output

** :-

1,1,A,B
2,A,B,C
3,3,C,D
4,D,E,F,G
5,5,E,F

x- is the 2nd column where I would like to assign NR when NF=4
n - This is the 2nd column.

Answer

Your question is not entirely clear.
In awk, the built-in variables NF and NR denote the number of fields in each line and the record/line number, respectively.

To get the desired output from the given input, I would do the following:

awk 'BEGIN{OFS=FS=","}$2=="x"{$2=NR}1' test.txt

This replaces each x in the second column by the line number:

1,1,A,B
2,A,B,C
3,3,C,D
4,D,E,F,G
5,5,E,F

Update: If you want to replace the 2nd column's content by NR if the number of fields equals 4:

awk 'BEGIN{OFS=FS=","}NF==4{$2=NR}1' test.txt

Output:

1,1,A,B
2,2,B,C
3,3,C,D
4,D,E,F,G
5,5,E,F