Reputation: 125
I'm using the following command to join the next row in a csv but would like do it without removing the rows.
awk 'NR%2{printf "%s, ",$0;next;}1' test.csv
Test.csv
rabbit
cat
dog
turtle
sheep
cow
Result:
rabbit, cat
dog, turtle
sheep, cow
Desired result:
rabbit, cat
cat, dog
dog, turtle
turtle, sheep
sheep, cow
cow, rabbit
any help would be appreciated
Upvotes: 1
Views: 183
Reputation: 133760
One more way to do this in GNU awk
, could you please try following. Written and tested with shown samples.
awk -v RS= -v OFS=', ' '
{
for(i=1;i<=(NF-1);i++){
print $i,$(i+1)
}
}
END{
print $NF,$1
}
' Input_file
Explanation: Adding detailed explanation here.
awk -v RS= -v OFS=', ' ' ##Starting awk program and setting RS as NULL here and setting OFS as comma with space here.
{
for(i=1;i<=(NF-1);i++){ ##Starting for loop from here till 2nd last field.
print $i,$(i+1) ##Printing current field and next field here.
}
}
END{ ##Starting END block of this code here.
print $NF,$1 ##Printing last field and first field as per OP question here.
}
' Input_file ##Mentioning Input_file name here.
Upvotes: 3
Reputation: 204558
$ awk -v OFS=', ' 'NR==1{first=$0} NR>1{print prev, $0} {prev=$0} END{print prev, first}' file
rabbit, cat
cat, dog
dog, turtle
turtle, sheep
sheep, cow
cow, rabbit
Upvotes: 2