I have a data like this:


I want to cut fields like that col1 and col3 should come together and col2 and col4 should come together.

So that my output variable should contain value like this.


Looking some help on this.

  • 1
    How many fields can you have? Will there always be 4? How many lines will you have? Only one or many? What scripting language will you be using? Should we assume bash-like syntax? Please edit your question and clarify. – terdon Feb 25 '16 at 10:11
  • 1
    echo "var1=col1,col2,col3,col4" | awk -F= '{print $2}' | awk -F, '{print $1","$3","$2","$4}' – Marware Feb 25 '16 at 10:16
  • Fields are dynamic. It can increase or decrease... – Sandeep Singh Feb 25 '16 at 13:37

With POSIX shells:

set -f
set -- $var1
unset var2 var3
while [ "$#" -ge 2 ]; do
  shift 2

With zsh:

unset var2 var3
for a b ("${(@s:,:)var1}") var2+=${var2+,}$a var3+=${var3+,}$b
  • It should work with Bourne shell too, shouldn't it? – cuonglm Feb 25 '16 at 14:17
  • 1
    @cuonglm, only if there are no empty cols. Some old versions of the Bourne shell didn't support -- or would print all the variables upon set --. set x $var1; shift would be needed there. Note that with POSIX compliant shells, my solution has a problem if the last col is empty. – Stéphane Chazelas Feb 25 '16 at 15:01
  • its working but leaving one additional comma at beaning. Is there any approach to trim those additional comma form this function itself. – Sandeep Singh Feb 26 '16 at 7:57
  • 1
    @SandeepSingh, possibly you're using an earlier revision of the answer where I had var2= var3= instead of unset var2 var3. ${var2+,} expands to , iif var2 is set, to avoid the leading ,. – Stéphane Chazelas Feb 26 '16 at 9:12
  • Yes, I was using earlier version of answer and then I was trimming it to remove leading ,.. Thanks for the clarification. – Sandeep Singh Feb 26 '16 at 10:28

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.