NamAshena
NamAshena

Reputation: 1737

How to join two consecutive lines together by awk

I have a text files with numbers, which I show a chunk of it hear:

4194369
4194376
4194383
4194377
4194389
4194394
4194399
4194395
4194402
4194403
4194407

I want to join two consecutive numbers in the file together, the following code dose the job for me, except it is not printing the last line, the output of the code is:

awk '{printf $0 (NR%2?",":"\n")}' file.txt
4194369,4194376
4194383,4194377
4194389,4194394
4194399,4194395
4194402,4194403

I wan to get this as output:

4194369,4194376
4194383,4194377
4194389,4194394
4194399,4194395
4194402,4194403
4194407

Upvotes: 2

Views: 247

Answers (4)

kvantour
kvantour

Reputation: 26471

time for old tools! paste is ideal for this

$ paste -sd',\n' file
4194369,4194376
4194383,4194377
4194389,4194394
4194399,4194395
4194402,4194403
4194407

Your awk could also be written as:

awk '(NR%2){printf "%s",$0; next}{print ","$0}END{if(NR%2) print ""}'

Upvotes: 2

RavinderSingh13
RavinderSingh13

Reputation: 133458

Could you please try following.

xargs -n 2 < Input_file  | tr -s ' ' ','

Output will be as follows.

4194369,4194376
4194383,4194377
4194389,4194394
4194399,4194395
4194402,4194403
4194407


EDIT: Trying to correct your attempt in awk as follows.

awk 'FNR%2==0{print val","$0;val="";next} {val=val?val OFS $0:$0} END{if(val != ""){print val}}'  Input_file

What was error in your approach, you are not checking next line's value(either it is present or not) so that is the reason if your Input_file is having ODD number of lines it will print comma(,) which is not suposed to happen.

Upvotes: 1

Ed Morton
Ed Morton

Reputation: 203229

$ awk -v OFS=, '!(NR%2){print p,$0} {p=$0} END{if (NR%2) print p}' file
4194369,4194376
4194383,4194377
4194389,4194394
4194399,4194395
4194402,4194403
4194407

Upvotes: 2

karakfa
karakfa

Reputation: 67467

time for new tools! pr is ideal for this

$ pr -2ats, file

4194369,4194376
4194383,4194377
4194389,4194394
4194399,4194395
4194402,4194403
4194407

Upvotes: 3

Related Questions