Print range of columns comma-separated, and the rest without comma-separation

I’m trying to figure this out.

awk '{print $1","$10","$11","$12","$13,$14,$15,$16,$17,$18,$19}' <<< "$PASTE_1" > test.csv

I need to print the $1 $10 $11 $12 separated by comma then continue with $13 until the of the line, without comma separation. Since there are many blank spaces from $13.

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

Do you mean something like this:

awk '{a = ""; for (i = 13 ; i <= NF ; i++) a = a $i; 
       print $1 "," $10 "," $11 "," $12 "," a}'

The input

a b c d e f g h i j k l m n o p q r s t u v w x y z

gives:

a,j,k,l,mnopqrstuvwxyz

That is, the fields starting from 13 are concatenated together, and then printed after 1, 10, 11 and 12.

Method 2

One way to do it:

awk -v OFS=, '{print $1, $10, $11, $12, ($13 $14 $15 $16 $17 $18 $19) }'

Method 3

perl -lane 'print join(",", @F[0,9..11], q//), @F[12..$#F]'

Explanation

  1. Array @F holds the fields in a line. @F[...] refers to a slice of elements of array @F. So, @F[0,9..11] is the slice consisting of the 1st, 10th to 12 elements of @F which are then join-ed together by comma and a dummy empty element q// is suffixed to the slice to generate the required , for the coming slice. The other slice @F[12..$#F] gathers the 13th till the last element of the @F array via the $#F which holds the last element’s idx. (Please note that array indexing is zero-starting in Perl).
  2. The various arguments to print are now joined together with the OFS = $, (defaults to null).


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x