Thulasi R
Thulasi R

Reputation: 321

How to print the first line of first column and second column as a single column with awk?

I am trying to print the first line of first column and second column into single column with awk. I am using the following awk one-liner

awk 'NR==1{printf $1 OFS; next}{print $2}' infile > new_file

Input:
A123 154.1
A123 158.1
A123 159.4

Expected Output:
A123
154.1
158.1
159.4

But the resulted output from the one-liner is as follows

A123 154.1
158.1
159.4

I would like to what mistake causes the change in output. I included '\n' in the code but not helping.

Thank you in advance

Upvotes: 2

Views: 4200

Answers (2)

Sundeep
Sundeep

Reputation: 23667

If this doesn't work, please add a better input/output sample.

$ awk 'NR==1{print $1} {print $2}' infile
A123
154.1
158.1
159.4

Also, output of awk command shown in the question doesn't match given sample. It should be this:

$ awk 'NR==1{printf $1 OFS; next}{print $2}' infile
A123 158.1
159.4

Unlike print function, printf doesn't add automatically add the value of ORS. And because of next, $2 of first line isn't printed.

Upvotes: 3

RavinderSingh13
RavinderSingh13

Reputation: 133458

1st solution: I would go with following approach so that we can handle multiple ids too, written and tested with shown samples in GNU awk.

awk '{a[$1]=(a[$1]?a[$1] ORS:"")$2} END{for(i in a){print i ORS a[i]}}' Input_file

2nd solution: Considering if your Input_file's 1st field is sorted then try following.

awk 'prev!=$1{print $1 ORS $2;prev=$1;next} {print $2}' Input_file

3rd solution: In case your Input_file is not sorted with 1st column then sort it and run the awk code.

sort -k1 Input_file | awk 'prev!=$1{print $1 ORS $2;prev=$1;next} {print $2}'

Upvotes: 2

Related Questions