2

I have data which are in "Key:value" form where keys are 901,902,903,904 and respective values are S,M,F,WAP`, with space as delimiter.

  • Input example
    901 S 902 M 903 F 904 WAP .....
    

I want to convert into key:value,key:value format.

  • Desired output:
    901:S,902:M,903:F,904:WAP .....
    

I tried using sed but I was only able to add asingle delimiter.

1
  • Is it a requirement to only use sed, or are other standard tools an option, too?
    – AdminBee
    Jan 20, 2023 at 10:19

2 Answers 2

2
$ sed -E 's/\s*([0-9]+)\s+([A-Z]+)/\1:\2,/g;s/,$//' <<< '901 S 902 M 903 F 904 WAP'
-------8<------------------
901:S,902:M,903:F,904:WAP
2

You can replace every odd space with a colon and every even space with a comma.

sed -E 's/ ([^ ]) /:\1,/g; s/ /:/'

The second substitution replaces the last remaining space with a colon - it's not replaced by the first substitution as there's no comma to go with it.

2
  • It's been working over over till specified length. --->> sed -E 's/ ([^ ]) /:\1,/g; s/ /:/' <<< '901:S,902:M,905:F,906:WAPENC 907 31 908 371 909 PLMN 913 NA 920' O/P :: 901:S,902:M,905:F,906:WAPENC:907 31 908 371 909 PLMN 913 NA 920 Expected O/P :: 901:S,902:M,905:F,906:WAPENC:907:31,908:371,909:PLMN,913:NA,920: and so on.
    – Sunny
    Jan 20, 2023 at 11:49
  • I don't understand. If your actual data is different to what you showed in the question, either edit the question, or ask a new one.
    – choroba
    Jan 20, 2023 at 12:17

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .