AWK series of numbers

Hi,

I have a dataset say

1 2 3 4
5 5 6 7
6 7 8 9 

I was wondering if there is a way to add another column with the following style...

1 2 3 4 xyz_1
5 5 6 7 xyz_2
6 7 8 9 xyz_3

It would be greatly appreciated if I can have an option of specifying what to write instead of xyz, range of values followed by xyz_ and the column.

The options for the above example would be

Text: xyz
range: 1-3
column: 5

awk '{ $(NF+1)="xyz_" ((NR%3)+1) } 1' file

Hi Corona,

Thanks a lot.

But I have more than 10000 rows and the one you gave me prints xyz_1, xyz_2 and xyz_3 repeatedly. I would like to have a series of numbers.

Thanks again.

You told me range 1-3, and I took that literally. What you want is actually much easier :stuck_out_tongue:

awk '{ $(NF+1)="xyz_" NR } 1' file

You the best.

Can you please explain it?

Thanks

NF is a special variable meaning 'number of fields'. $ is an operator that turns a number into a field. So $NF would be the last field.

$(NF+1) would be the field after the last field, then. So we're adding a new field.

The field is "xyz_", followed by the special variable NR, "number of records", generally the same thing as lines. Putting two things in a row concatenates them.

The '1' on the end is an expression which makes it print every line. It could be a regex if you only wanted it to print lines containing a certain string, or a comparision involving variables if you wanted to do more complicated logic based on things set previously.

The whole thing is done repeatedly, once per line, since there's no condition before the code block. If you did NR==1 { ... } 1 then it would only run the code block for the very first line ( though it would still print every line).

$ nawk '$NF=$NF" xyz_"NR' test.txt
1 2 3 4 xyz_1
5 5 6 7 xyz_2
6 7 8 9 xyz_3
awk '{ print $0 " xyz_" NR } ' file

Great!

Cool. Never knew awk could do this pages of code in a single line.

Thanks to all you genius minds.

Any perfect source for learning these things?